No messages were sent.
diff --git a/pkg/enqueue-bundle/Tests/Functional/App/AbstractAsyncListener.php b/pkg/enqueue-bundle/Tests/Functional/App/AbstractAsyncListener.php
new file mode 100644
index 000000000..acf7406e1
--- /dev/null
+++ b/pkg/enqueue-bundle/Tests/Functional/App/AbstractAsyncListener.php
@@ -0,0 +1,48 @@
+producer = $producer;
+ $this->registry = $registry;
+ }
+
+ /**
+ * @param Event|ContractEvent $event
+ * @param string $eventName
+ */
+ protected function onEventInternal($event, $eventName)
+ {
+ if (false == $this->isSyncMode($eventName)) {
+ $transformerName = $this->registry->getTransformerNameForEvent($eventName);
+
+ $interopMessage = $this->registry->getTransformer($transformerName)->toMessage($eventName, $event);
+ $message = new Message($interopMessage->getBody());
+ $message->setScope(Message::SCOPE_APP);
+ $message->setProperty('event_name', $eventName);
+ $message->setProperty('transformer_name', $transformerName);
+
+ $this->producer->sendCommand(Commands::DISPATCH_ASYNC_EVENTS, $message);
+ }
+ }
+}
diff --git a/pkg/enqueue-bundle/Tests/Functional/App/AppKernel.php b/pkg/enqueue-bundle/Tests/Functional/App/AppKernel.php
index e484f0bfd..5ec2e75cd 100644
--- a/pkg/enqueue-bundle/Tests/Functional/App/AppKernel.php
+++ b/pkg/enqueue-bundle/Tests/Functional/App/AppKernel.php
@@ -7,10 +7,7 @@
class AppKernel extends Kernel
{
- /**
- * @return array
- */
- public function registerBundles()
+ public function registerBundles(): iterable
{
$bundles = [
new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
@@ -21,31 +18,22 @@ public function registerBundles()
return $bundles;
}
- /**
- * @return string
- */
- public function getCacheDir()
+ public function getCacheDir(): string
{
return sys_get_temp_dir().'/EnqueueBundle/cache';
}
- /**
- * @return string
- */
- public function getLogDir()
+ public function getLogDir(): string
{
return sys_get_temp_dir().'/EnqueueBundle/cache/logs';
}
- /**
- * @param \Symfony\Component\Config\Loader\LoaderInterface $loader
- */
- public function registerContainerConfiguration(LoaderInterface $loader)
+ public function registerContainerConfiguration(LoaderInterface $loader): void
{
$loader->load(__DIR__.'/config/config.yml');
}
- protected function getContainerClass()
+ protected function getContainerClass(): string
{
return parent::getContainerClass().'BundleDefault';
}
diff --git a/pkg/enqueue-bundle/Tests/Functional/App/AsyncListener.php b/pkg/enqueue-bundle/Tests/Functional/App/AsyncListener.php
index 9e94c2c6f..23ab4af79 100644
--- a/pkg/enqueue-bundle/Tests/Functional/App/AsyncListener.php
+++ b/pkg/enqueue-bundle/Tests/Functional/App/AsyncListener.php
@@ -2,50 +2,15 @@
namespace Enqueue\Bundle\Tests\Functional\App;
-use Enqueue\AsyncEventDispatcher\Commands;
-use Enqueue\AsyncEventDispatcher\Registry;
-use Enqueue\Client\Message;
-use Enqueue\Client\ProducerInterface;
-use Symfony\Component\EventDispatcher\Event;
+use Symfony\Contracts\EventDispatcher\Event;
-class AsyncListener extends \Enqueue\AsyncEventDispatcher\AsyncListener
+class AsyncListener extends AbstractAsyncListener
{
/**
- * @var ProducerInterface
- */
- private $producer;
-
- /**
- * @var Registry
- */
- private $registry;
-
- /**
- * @param ProducerInterface $producer
- * @param Registry $registry
- */
- public function __construct(ProducerInterface $producer, Registry $registry)
- {
- $this->producer = $producer;
- $this->registry = $registry;
- }
-
- /**
- * @param Event $event
* @param string $eventName
*/
- public function onEvent(Event $event = null, $eventName)
+ public function onEvent(Event $event, $eventName)
{
- if (false == $this->isSyncMode($eventName)) {
- $transformerName = $this->registry->getTransformerNameForEvent($eventName);
-
- $interopMessage = $this->registry->getTransformer($transformerName)->toMessage($eventName, $event);
- $message = new Message($interopMessage->getBody());
- $message->setScope(Message::SCOPE_APP);
- $message->setProperty('event_name', $eventName);
- $message->setProperty('transformer_name', $transformerName);
-
- $this->producer->sendCommand(Commands::DISPATCH_ASYNC_EVENTS, $message);
- }
+ $this->onEventInternal($event, $eventName);
}
}
diff --git a/pkg/enqueue-bundle/Tests/Functional/App/CustomAppKernel.php b/pkg/enqueue-bundle/Tests/Functional/App/CustomAppKernel.php
index ed05537e4..5009adc69 100644
--- a/pkg/enqueue-bundle/Tests/Functional/App/CustomAppKernel.php
+++ b/pkg/enqueue-bundle/Tests/Functional/App/CustomAppKernel.php
@@ -7,7 +7,7 @@
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\Kernel;
-use Symfony\Component\Routing\RouteCollectionBuilder;
+use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
class CustomAppKernel extends Kernel
{
@@ -16,19 +16,21 @@ class CustomAppKernel extends Kernel
private $enqueueConfigId;
private $enqueueConfig = [
- 'client' => [
- 'prefix' => 'enqueue',
- 'app_name' => '',
- 'router_topic' => 'test',
- 'router_queue' => 'test',
- 'default_processor_queue' => 'test',
+ 'default' => [
+ 'client' => [
+ 'prefix' => 'enqueue',
+ 'app_name' => '',
+ 'router_topic' => 'test',
+ 'router_queue' => 'test',
+ 'default_queue' => 'test',
+ ],
],
];
- public function setEnqueueConfig(array $config)
+ public function setEnqueueConfig(array $config): void
{
$this->enqueueConfig = array_replace_recursive($this->enqueueConfig, $config);
- $this->enqueueConfig['client']['app_name'] = str_replace('.', '', uniqid('app_name', true));
+ $this->enqueueConfig['default']['client']['app_name'] = str_replace('.', '', uniqid('app_name', true));
$this->enqueueConfigId = md5(json_encode($this->enqueueConfig));
$fs = new Filesystem();
@@ -36,10 +38,7 @@ public function setEnqueueConfig(array $config)
$fs->mkdir(sys_get_temp_dir().'/EnqueueBundleCustom/cache/'.$this->enqueueConfigId);
}
- /**
- * @return array
- */
- public function registerBundles()
+ public function registerBundles(): iterable
{
$bundles = [
new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
@@ -50,41 +49,28 @@ public function registerBundles()
return $bundles;
}
- /**
- * @return string
- */
- public function getCacheDir()
+ public function getCacheDir(): string
{
return sys_get_temp_dir().'/EnqueueBundleCustom/cache/'.$this->enqueueConfigId;
}
- /**
- * @return string
- */
- public function getLogDir()
+ public function getLogDir(): string
{
return sys_get_temp_dir().'/EnqueueBundleCustom/cache/logs/'.$this->enqueueConfigId;
}
- protected function getContainerClass()
+ protected function getContainerClass(): string
{
return parent::getContainerClass().'Custom'.$this->enqueueConfigId;
}
- /**
- * {@inheritdoc}
- */
- protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
+ protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader): void
{
$loader->load(__DIR__.'/config/custom-config.yml');
-
$c->loadFromExtension('enqueue', $this->enqueueConfig);
}
- /**
- * {@inheritdoc}
- */
- protected function configureRoutes(RouteCollectionBuilder $routes)
+ protected function configureRoutes(RoutingConfigurator $routes)
{
}
}
diff --git a/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncEventTransformer.php b/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncEventTransformer.php
index 63d6df75a..0a83a04b6 100644
--- a/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncEventTransformer.php
+++ b/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncEventTransformer.php
@@ -6,8 +6,8 @@
use Enqueue\Util\JSON;
use Interop\Queue\Context;
use Interop\Queue\Message;
-use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\GenericEvent;
+use Symfony\Contracts\EventDispatcher\Event;
class TestAsyncEventTransformer implements EventTransformer
{
@@ -16,17 +16,14 @@ class TestAsyncEventTransformer implements EventTransformer
*/
private $context;
- /**
- * @param Context $context
- */
public function __construct(Context $context)
{
$this->context = $context;
}
- public function toMessage($eventName, Event $event)
+ public function toMessage($eventName, ?Event $event = null)
{
- if (Event::class === get_class($event)) {
+ if (Event::class === $event::class) {
return $this->context->createMessage(json_encode(''));
}
diff --git a/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncListener.php b/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncListener.php
index aa4884bca..fd0ec1d91 100644
--- a/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncListener.php
+++ b/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncListener.php
@@ -2,14 +2,13 @@
namespace Enqueue\Bundle\Tests\Functional\App;
-use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class TestAsyncListener
{
public $calls = [];
- public function onEvent(Event $event, $eventName, EventDispatcherInterface $dispatcher)
+ public function onEvent($event, $eventName, EventDispatcherInterface $dispatcher)
{
$this->calls[] = func_get_args();
}
diff --git a/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncSubscriber.php b/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncSubscriber.php
index 2b45bed6e..a52a9f7ab 100644
--- a/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncSubscriber.php
+++ b/pkg/enqueue-bundle/Tests/Functional/App/TestAsyncSubscriber.php
@@ -2,7 +2,6 @@
namespace Enqueue\Bundle\Tests\Functional\App;
-use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
@@ -10,12 +9,12 @@ class TestAsyncSubscriber implements EventSubscriberInterface
{
public $calls = [];
- public function onEvent(Event $event, $eventName, EventDispatcherInterface $dispatcher)
+ public function onEvent($event, $eventName, EventDispatcherInterface $dispatcher)
{
$this->calls[] = func_get_args();
}
- public static function getSubscribedEvents()
+ public static function getSubscribedEvents(): array
{
return ['test_async_subscriber' => 'onEvent'];
}
diff --git a/pkg/enqueue-bundle/Tests/Functional/App/config/config.yml b/pkg/enqueue-bundle/Tests/Functional/App/config/config.yml
index ac50e5afa..d3ca2a37f 100644
--- a/pkg/enqueue-bundle/Tests/Functional/App/config/config.yml
+++ b/pkg/enqueue-bundle/Tests/Functional/App/config/config.yml
@@ -8,11 +8,10 @@ framework:
#translator: { fallback: "%locale%" }
test: ~
assets: false
- templating: false
session:
- storage_id: session.storage.mock_file
+ storage_factory_id: session.storage.factory.mock_file
secret: '%secret%'
- router: { resource: '%kernel.root_dir%/config/routing.yml' }
+ router: { resource: '%kernel.project_dir%/config/routing.yml' }
default_locale: '%locale%'
doctrine:
@@ -22,12 +21,17 @@ doctrine:
charset: UTF8
enqueue:
- transport: 'null:'
- client:
- traceable_producer: true
- job: true
- async_events: true
- async_commands: true
+ default:
+ transport: 'null:'
+ client:
+ traceable_producer: true
+ job: true
+ async_events: true
+ async_commands:
+ enabled: true
+ timeout: 60
+ command_name: ~
+ queue_name: ~
services:
test_enqueue.client.default.traceable_producer:
@@ -74,11 +78,15 @@ services:
alias: 'enqueue.client.routes_command'
public: true
+ test.enqueue.events.async_processor:
+ alias: 'enqueue.events.async_processor'
+ public: true
+
test_async_listener:
class: 'Enqueue\Bundle\Tests\Functional\App\TestAsyncListener'
public: true
tags:
- - { name: 'kernel.event_listener', async: true, event: 'test_async', method: 'onEvent' }
+ - { name: 'kernel.event_listener', async: true, event: 'test_async', method: 'onEvent', dispatcher: 'enqueue.events.event_dispatcher' }
test_command_subscriber_processor:
class: 'Enqueue\Bundle\Tests\Functional\App\TestCommandSubscriberProcessor'
@@ -102,7 +110,7 @@ services:
class: 'Enqueue\Bundle\Tests\Functional\App\TestAsyncSubscriber'
public: true
tags:
- - { name: 'kernel.event_subscriber', async: true }
+ - { name: 'kernel.event_subscriber', async: true, dispatcher: 'enqueue.events.event_dispatcher' }
test_async_event_transformer:
class: 'Enqueue\Bundle\Tests\Functional\App\TestAsyncEventTransformer'
@@ -117,4 +125,4 @@ services:
enqueue.events.async_listener:
class: 'Enqueue\Bundle\Tests\Functional\App\AsyncListener'
public: true
- arguments: ['@enqueue.client.default.producer', '@enqueue.events.registry']
\ No newline at end of file
+ arguments: ['@enqueue.client.default.producer', '@enqueue.events.registry']
diff --git a/pkg/enqueue-bundle/Tests/Functional/App/config/custom-config.yml b/pkg/enqueue-bundle/Tests/Functional/App/config/custom-config.yml
index 978da5d18..d02f3002d 100644
--- a/pkg/enqueue-bundle/Tests/Functional/App/config/custom-config.yml
+++ b/pkg/enqueue-bundle/Tests/Functional/App/config/custom-config.yml
@@ -7,13 +7,20 @@ framework:
#translator: { fallback: "%locale%" }
test: ~
assets: false
- templating: false
session:
- storage_id: session.storage.mock_file
+ storage_factory_id: session.storage.factory.mock_file
secret: '%secret%'
- router: { resource: '%kernel.root_dir%/config/routing.yml' }
+ router: { resource: '%kernel.project_dir%/config/routing.yml' }
default_locale: '%locale%'
+doctrine:
+ dbal:
+ connections:
+ custom:
+ url: "%env(DOCTRINE_DSN)%"
+ driver: pdo_mysql
+ charset: UTF8
+
services:
test_enqueue.client.default.driver:
alias: 'enqueue.client.default.driver'
@@ -23,6 +30,10 @@ services:
alias: 'enqueue.client.default.producer'
public: true
+ test_enqueue.client.default.lazy_producer:
+ alias: 'enqueue.client.default.lazy_producer'
+ public: true
+
test_enqueue.transport.default.context:
alias: 'enqueue.transport.default.context'
public: true
@@ -70,4 +81,4 @@ services:
test.sqs_custom_connection_factory_factory:
class: 'Enqueue\Bundle\Tests\Functional\App\SqsCustomConnectionFactoryFactory'
- arguments: ['@service_container']
\ No newline at end of file
+ arguments: ['@service_container']
diff --git a/pkg/enqueue-bundle/Tests/Functional/Client/ProducerTest.php b/pkg/enqueue-bundle/Tests/Functional/Client/ProducerTest.php
index 51db9dc25..29a96aa7d 100644
--- a/pkg/enqueue-bundle/Tests/Functional/Client/ProducerTest.php
+++ b/pkg/enqueue-bundle/Tests/Functional/Client/ProducerTest.php
@@ -4,7 +4,6 @@
use Enqueue\Bundle\Tests\Functional\WebTestCase;
use Enqueue\Client\Message;
-use Enqueue\Client\Producer;
use Enqueue\Client\ProducerInterface;
use Enqueue\Client\TraceableProducer;
use Enqueue\Rpc\Promise;
diff --git a/pkg/enqueue-bundle/Tests/Functional/Events/AsyncListenerTest.php b/pkg/enqueue-bundle/Tests/Functional/Events/AsyncListenerTest.php
index 6e952ab28..7fb6fdd86 100644
--- a/pkg/enqueue-bundle/Tests/Functional/Events/AsyncListenerTest.php
+++ b/pkg/enqueue-bundle/Tests/Functional/Events/AsyncListenerTest.php
@@ -16,7 +16,7 @@
*/
class AsyncListenerTest extends WebTestCase
{
- public function setUp()
+ protected function setUp(): void
{
parent::setUp();
@@ -33,7 +33,7 @@ public function testShouldNotCallRealListenerIfMarkedAsAsync()
/** @var EventDispatcherInterface $dispatcher */
$dispatcher = static::$container->get('event_dispatcher');
- $dispatcher->dispatch('test_async', new GenericEvent('aSubject'));
+ $this->dispatch($dispatcher, new GenericEvent('aSubject'), 'test_async');
/** @var TestAsyncListener $listener */
$listener = static::$container->get('test_async_listener');
@@ -48,7 +48,7 @@ public function testShouldSendMessageToExpectedCommandInsteadOfCallingRealListen
$event = new GenericEvent('theSubject', ['fooArg' => 'fooVal']);
- $dispatcher->dispatch('test_async', $event);
+ $this->dispatch($dispatcher, $event, 'test_async');
/** @var TraceableProducer $producer */
$producer = static::$container->get('test_enqueue.client.default.producer');
@@ -66,9 +66,9 @@ public function testShouldSendMessageForEveryDispatchCall()
/** @var EventDispatcherInterface $dispatcher */
$dispatcher = static::$container->get('event_dispatcher');
- $dispatcher->dispatch('test_async', new GenericEvent('theSubject', ['fooArg' => 'fooVal']));
- $dispatcher->dispatch('test_async', new GenericEvent('theSubject', ['fooArg' => 'fooVal']));
- $dispatcher->dispatch('test_async', new GenericEvent('theSubject', ['fooArg' => 'fooVal']));
+ $this->dispatch($dispatcher, new GenericEvent('theSubject', ['fooArg' => 'fooVal']), 'test_async');
+ $this->dispatch($dispatcher, new GenericEvent('theSubject', ['fooArg' => 'fooVal']), 'test_async');
+ $this->dispatch($dispatcher, new GenericEvent('theSubject', ['fooArg' => 'fooVal']), 'test_async');
/** @var TraceableProducer $producer */
$producer = static::$container->get('test_enqueue.client.default.producer');
@@ -84,11 +84,11 @@ public function testShouldSendMessageIfDispatchedFromInsideListener()
$dispatcher = static::$container->get('event_dispatcher');
$eventName = 'an_event_'.uniqid();
- $dispatcher->addListener($eventName, function (Event $event, $eventName, EventDispatcherInterface $dispatcher) {
- $dispatcher->dispatch('test_async', new GenericEvent('theSubject', ['fooArg' => 'fooVal']));
+ $dispatcher->addListener($eventName, function ($event, $eventName, EventDispatcherInterface $dispatcher) {
+ $this->dispatch($dispatcher, new GenericEvent('theSubject', ['fooArg' => 'fooVal']), 'test_async');
});
- $dispatcher->dispatch($eventName);
+ $this->dispatch($dispatcher, new GenericEvent(), $eventName);
/** @var TraceableProducer $producer */
$producer = static::$container->get('test_enqueue.client.default.producer');
@@ -97,4 +97,15 @@ public function testShouldSendMessageIfDispatchedFromInsideListener()
$this->assertCount(1, $traces);
}
+
+ private function dispatch(EventDispatcherInterface $dispatcher, $event, $eventName): void
+ {
+ if (!class_exists(Event::class)) {
+ // Symfony 5
+ $dispatcher->dispatch($event, $eventName);
+ } else {
+ // Symfony < 5
+ $dispatcher->dispatch($eventName, $event);
+ }
+ }
}
diff --git a/pkg/enqueue-bundle/Tests/Functional/Events/AsyncProcessorTest.php b/pkg/enqueue-bundle/Tests/Functional/Events/AsyncProcessorTest.php
index 101e5ecec..d85567509 100644
--- a/pkg/enqueue-bundle/Tests/Functional/Events/AsyncProcessorTest.php
+++ b/pkg/enqueue-bundle/Tests/Functional/Events/AsyncProcessorTest.php
@@ -18,7 +18,7 @@
*/
class AsyncProcessorTest extends WebTestCase
{
- public function setUp()
+ protected function setUp(): void
{
parent::setUp();
@@ -33,7 +33,7 @@ public function setUp()
public function testCouldBeGetFromContainerAsService()
{
/** @var AsyncProcessor $processor */
- $processor = static::$container->get('enqueue.events.async_processor');
+ $processor = static::$container->get('test.enqueue.events.async_processor');
$this->assertInstanceOf(AsyncProcessor::class, $processor);
}
@@ -41,7 +41,7 @@ public function testCouldBeGetFromContainerAsService()
public function testShouldRejectIfMessageDoesNotContainEventNameProperty()
{
/** @var AsyncProcessor $processor */
- $processor = static::$container->get('enqueue.events.async_processor');
+ $processor = static::$container->get('test.enqueue.events.async_processor');
$message = new NullMessage();
@@ -51,7 +51,7 @@ public function testShouldRejectIfMessageDoesNotContainEventNameProperty()
public function testShouldRejectIfMessageDoesNotContainTransformerNameProperty()
{
/** @var AsyncProcessor $processor */
- $processor = static::$container->get('enqueue.events.async_processor');
+ $processor = static::$container->get('test.enqueue.events.async_processor');
$message = new NullMessage();
$message->setProperty('event_name', 'anEventName');
@@ -62,7 +62,7 @@ public function testShouldRejectIfMessageDoesNotContainTransformerNameProperty()
public function testShouldCallRealListener()
{
/** @var AsyncProcessor $processor */
- $processor = static::$container->get('enqueue.events.async_processor');
+ $processor = static::$container->get('test.enqueue.events.async_processor');
$message = new NullMessage();
$message->setProperty('event_name', 'test_async');
@@ -93,7 +93,7 @@ public function testShouldCallRealListener()
public function testShouldCallRealSubscriber()
{
/** @var AsyncProcessor $processor */
- $processor = static::$container->get('enqueue.events.async_processor');
+ $processor = static::$container->get('test.enqueue.events.async_processor');
$message = new NullMessage();
$message->setProperty('event_name', 'test_async_subscriber');
diff --git a/pkg/enqueue-bundle/Tests/Functional/Events/AsyncSubscriberTest.php b/pkg/enqueue-bundle/Tests/Functional/Events/AsyncSubscriberTest.php
index 6e00eafca..4b145524a 100644
--- a/pkg/enqueue-bundle/Tests/Functional/Events/AsyncSubscriberTest.php
+++ b/pkg/enqueue-bundle/Tests/Functional/Events/AsyncSubscriberTest.php
@@ -16,7 +16,7 @@
*/
class AsyncSubscriberTest extends WebTestCase
{
- public function setUp()
+ protected function setUp(): void
{
parent::setUp();
@@ -33,7 +33,7 @@ public function testShouldNotCallRealSubscriberIfMarkedAsAsync()
/** @var EventDispatcherInterface $dispatcher */
$dispatcher = static::$container->get('event_dispatcher');
- $dispatcher->dispatch('test_async_subscriber', new GenericEvent('aSubject'));
+ $this->dispatch($dispatcher, new GenericEvent('aSubject'), 'test_async_subscriber');
/** @var TestAsyncSubscriber $listener */
$listener = static::$container->get('test_async_subscriber');
@@ -48,7 +48,7 @@ public function testShouldSendMessageToExpectedTopicInsteadOfCallingRealSubscrib
$event = new GenericEvent('theSubject', ['fooArg' => 'fooVal']);
- $dispatcher->dispatch('test_async_subscriber', $event);
+ $this->dispatch($dispatcher, $event, 'test_async_subscriber');
/** @var TraceableProducer $producer */
$producer = static::$container->get('test_enqueue.client.default.producer');
@@ -66,9 +66,9 @@ public function testShouldSendMessageForEveryDispatchCall()
/** @var EventDispatcherInterface $dispatcher */
$dispatcher = static::$container->get('event_dispatcher');
- $dispatcher->dispatch('test_async_subscriber', new GenericEvent('theSubject', ['fooArg' => 'fooVal']));
- $dispatcher->dispatch('test_async_subscriber', new GenericEvent('theSubject', ['fooArg' => 'fooVal']));
- $dispatcher->dispatch('test_async_subscriber', new GenericEvent('theSubject', ['fooArg' => 'fooVal']));
+ $this->dispatch($dispatcher, new GenericEvent('theSubject', ['fooArg' => 'fooVal']), 'test_async_subscriber');
+ $this->dispatch($dispatcher, new GenericEvent('theSubject', ['fooArg' => 'fooVal']), 'test_async_subscriber');
+ $this->dispatch($dispatcher, new GenericEvent('theSubject', ['fooArg' => 'fooVal']), 'test_async_subscriber');
/** @var TraceableProducer $producer */
$producer = static::$container->get('test_enqueue.client.default.producer');
@@ -84,11 +84,11 @@ public function testShouldSendMessageIfDispatchedFromInsideListener()
$dispatcher = static::$container->get('event_dispatcher');
$eventName = 'anEvent'.uniqid();
- $dispatcher->addListener($eventName, function (Event $event, $eventName, EventDispatcherInterface $dispatcher) {
- $dispatcher->dispatch('test_async_subscriber', new GenericEvent('theSubject', ['fooArg' => 'fooVal']));
+ $dispatcher->addListener($eventName, function ($event, $eventName, EventDispatcherInterface $dispatcher) {
+ $this->dispatch($dispatcher, new GenericEvent('theSubject', ['fooArg' => 'fooVal']), 'test_async_subscriber');
});
- $dispatcher->dispatch($eventName);
+ $this->dispatch($dispatcher, new GenericEvent(), $eventName);
/** @var TraceableProducer $producer */
$producer = static::$container->get('test_enqueue.client.default.producer');
@@ -97,4 +97,15 @@ public function testShouldSendMessageIfDispatchedFromInsideListener()
$this->assertCount(1, $traces);
}
+
+ private function dispatch(EventDispatcherInterface $dispatcher, $event, $eventName): void
+ {
+ if (!class_exists(Event::class)) {
+ // Symfony 5
+ $dispatcher->dispatch($event, $eventName);
+ } else {
+ // Symfony < 5
+ $dispatcher->dispatch($eventName, $event);
+ }
+ }
}
diff --git a/pkg/enqueue-bundle/Tests/Functional/LazyProducerTest.php b/pkg/enqueue-bundle/Tests/Functional/LazyProducerTest.php
new file mode 100644
index 000000000..18375aef3
--- /dev/null
+++ b/pkg/enqueue-bundle/Tests/Functional/LazyProducerTest.php
@@ -0,0 +1,64 @@
+customSetUp([
+ 'default' => [
+ 'transport' => [
+ 'dsn' => 'invalidDSN',
+ ],
+ ],
+ ]);
+
+ /** @var LazyProducer $producer */
+ $producer = static::$container->get('test_enqueue.client.default.lazy_producer');
+ $this->assertInstanceOf(LazyProducer::class, $producer);
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The DSN is invalid.');
+ $producer->sendEvent('foo', 'foo');
+ }
+
+ public static function getKernelClass(): string
+ {
+ include_once __DIR__.'/App/CustomAppKernel.php';
+
+ return CustomAppKernel::class;
+ }
+
+ protected function customSetUp(array $enqueueConfig)
+ {
+ static::$class = null;
+
+ static::$client = static::createClient(['enqueue_config' => $enqueueConfig]);
+ static::$client->getKernel()->boot();
+ static::$kernel = static::$client->getKernel();
+ static::$container = static::$kernel->getContainer();
+ }
+
+ protected static function createKernel(array $options = []): CustomAppKernel
+ {
+ /** @var CustomAppKernel $kernel */
+ $kernel = parent::createKernel($options);
+
+ $kernel->setEnqueueConfig(isset($options['enqueue_config']) ? $options['enqueue_config'] : []);
+
+ return $kernel;
+ }
+}
diff --git a/pkg/enqueue-bundle/Tests/Functional/RoutesCommandTest.php b/pkg/enqueue-bundle/Tests/Functional/RoutesCommandTest.php
index afefe6482..66833b1ce 100644
--- a/pkg/enqueue-bundle/Tests/Functional/RoutesCommandTest.php
+++ b/pkg/enqueue-bundle/Tests/Functional/RoutesCommandTest.php
@@ -25,12 +25,12 @@ public function testShouldDisplayRegisteredTopics()
$tester = new CommandTester($command);
$tester->execute([]);
- $expected = <<<'OUTPUT'
-| topic | theTopic | default (prefixed) | test_topic_subscriber_processor | (hidden) |
-OUTPUT;
-
$this->assertSame(0, $tester->getStatusCode());
- $this->assertContains($expected, $tester->getDisplay());
+ $this->assertStringContainsString('| topic', $tester->getDisplay());
+ $this->assertStringContainsString('| theTopic', $tester->getDisplay());
+ $this->assertStringContainsString('| default (prefixed)', $tester->getDisplay());
+ $this->assertStringContainsString('| test_topic_subscriber_processor', $tester->getDisplay());
+ $this->assertStringContainsString('| (hidden)', $tester->getDisplay());
}
public function testShouldDisplayCommands()
@@ -41,11 +41,11 @@ public function testShouldDisplayCommands()
$tester = new CommandTester($command);
$tester->execute([]);
- $expected = <<<'OUTPUT'
-| command | theCommand | default (prefixed) | test_command_subscriber_processor | (hidden) |
-OUTPUT;
-
$this->assertSame(0, $tester->getStatusCode());
- $this->assertContains($expected, $tester->getDisplay());
+ $this->assertStringContainsString('| command', $tester->getDisplay());
+ $this->assertStringContainsString('| theCommand', $tester->getDisplay());
+ $this->assertStringContainsString('| test_command_subscriber_processor', $tester->getDisplay());
+ $this->assertStringContainsString('| default (prefixed)', $tester->getDisplay());
+ $this->assertStringContainsString('| (hidden)', $tester->getDisplay());
}
}
diff --git a/pkg/enqueue-bundle/Tests/Functional/TestCommandProcessor.php b/pkg/enqueue-bundle/Tests/Functional/TestCommandProcessor.php
index 5875a865b..dfc2bb864 100644
--- a/pkg/enqueue-bundle/Tests/Functional/TestCommandProcessor.php
+++ b/pkg/enqueue-bundle/Tests/Functional/TestCommandProcessor.php
@@ -9,7 +9,7 @@
class TestCommandProcessor implements Processor, CommandSubscriberInterface
{
- const COMMAND = 'test-command';
+ public const COMMAND = 'test-command';
/**
* @var Message
diff --git a/pkg/enqueue-bundle/Tests/Functional/TestProcessor.php b/pkg/enqueue-bundle/Tests/Functional/TestProcessor.php
index 8d21cb7ac..9b54bdf2d 100644
--- a/pkg/enqueue-bundle/Tests/Functional/TestProcessor.php
+++ b/pkg/enqueue-bundle/Tests/Functional/TestProcessor.php
@@ -9,7 +9,7 @@
class TestProcessor implements Processor, TopicSubscriberInterface
{
- const TOPIC = 'test-topic';
+ public const TOPIC = 'test-topic';
/**
* @var Message
diff --git a/pkg/enqueue-bundle/Tests/Functional/UseCasesTest.php b/pkg/enqueue-bundle/Tests/Functional/UseCasesTest.php
index 6a9f085bf..7417412bd 100644
--- a/pkg/enqueue-bundle/Tests/Functional/UseCasesTest.php
+++ b/pkg/enqueue-bundle/Tests/Functional/UseCasesTest.php
@@ -11,31 +11,26 @@
use Interop\Queue\Message;
use Interop\Queue\Queue;
use Symfony\Component\Console\Tester\CommandTester;
-use Symfony\Component\Filesystem\Filesystem;
/**
* @group functional
*/
class UseCasesTest extends WebTestCase
{
- public function setUp()
+ private const RECEIVE_TIMEOUT = 500;
+
+ protected function setUp(): void
{
// do not call parent::setUp.
// parent::setUp();
}
- public function tearDown()
+ protected function tearDown(): void
{
if ($this->getContext()) {
$this->getContext()->close();
}
- if (static::$kernel) {
- $fs = new Filesystem();
- $fs->remove(static::$kernel->getLogDir());
- $fs->remove(static::$kernel->getCacheDir());
- }
-
parent::tearDown();
}
@@ -50,76 +45,113 @@ public function provideEnqueueConfigs()
$this->assertDirectoryExists($certDir);
yield 'amqp_dsn' => [[
- 'transport' => getenv('AMQP_DSN'),
+ 'default' => [
+ 'transport' => getenv('AMQP_DSN'),
+ ],
]];
yield 'amqps_dsn' => [[
- 'transport' => [
- 'dsn' => getenv('AMQPS_DSN'),
- 'ssl_verify' => false,
- 'ssl_cacert' => $certDir.'/cacert.pem',
- 'ssl_cert' => $certDir.'/cert.pem',
- 'ssl_key' => $certDir.'/key.pem',
+ 'default' => [
+ 'transport' => [
+ 'dsn' => getenv('AMQPS_DSN'),
+ 'ssl_verify' => false,
+ 'ssl_cacert' => $certDir.'/cacert.pem',
+ 'ssl_cert' => $certDir.'/cert.pem',
+ 'ssl_key' => $certDir.'/key.pem',
+ ],
],
]];
yield 'dsn_as_env' => [[
- 'transport' => '%env(AMQP_DSN)%',
+ 'default' => [
+ 'transport' => '%env(AMQP_DSN)%',
+ ],
]];
yield 'dbal_dsn' => [[
- 'transport' => getenv('DOCTRINE_DSN'),
+ 'default' => [
+ 'transport' => getenv('DOCTRINE_DSN'),
+ ],
]];
yield 'rabbitmq_stomp' => [[
- 'transport' => [
- 'dsn' => getenv('RABITMQ_STOMP_DSN'),
- 'lazy' => false,
- 'management_plugin_installed' => true,
+ 'default' => [
+ 'transport' => [
+ 'dsn' => getenv('RABITMQ_STOMP_DSN'),
+ 'lazy' => false,
+ 'management_plugin_installed' => true,
+ ],
],
]];
yield 'predis_dsn' => [[
- 'transport' => [
- 'dsn' => getenv('PREDIS_DSN'),
- 'lazy' => false,
+ 'default' => [
+ 'transport' => [
+ 'dsn' => getenv('PREDIS_DSN'),
+ 'lazy' => false,
+ ],
],
]];
yield 'phpredis_dsn' => [[
- 'transport' => [
- 'dsn' => getenv('PHPREDIS_DSN'),
- 'lazy' => false,
+ 'default' => [
+ 'transport' => [
+ 'dsn' => getenv('PHPREDIS_DSN'),
+ 'lazy' => false,
+ ],
],
]];
yield 'fs_dsn' => [[
- 'transport' => 'file://'.sys_get_temp_dir(),
+ 'default' => [
+ 'transport' => 'file://'.sys_get_temp_dir(),
+ ],
]];
yield 'sqs' => [[
- 'transport' => [
- 'dsn' => getenv('SQS_DSN'),
+ 'default' => [
+ 'transport' => [
+ 'dsn' => getenv('SQS_DSN'),
+ ],
],
]];
yield 'sqs_client' => [[
- 'transport' => [
- 'dsn' => 'sqs:',
- 'service' => 'test.sqs_client',
- 'factory_service' => 'test.sqs_custom_connection_factory_factory',
+ 'default' => [
+ 'transport' => [
+ 'dsn' => 'sqs:',
+ 'service' => 'test.sqs_client',
+ 'factory_service' => 'test.sqs_custom_connection_factory_factory',
+ ],
],
]];
yield 'mongodb_dsn' => [[
- 'transport' => getenv('MONGO_DSN'),
+ 'default' => [
+ 'transport' => getenv('MONGO_DSN'),
+ ],
+ ]];
+
+ yield 'doctrine' => [[
+ 'default' => [
+ 'transport' => 'doctrine://custom',
+ ],
]];
-//
-// yield 'gps' => [[
-// 'transport' => [
-// 'dsn' => getenv('GPS_DSN'),
-// ],
-// ]];
+
+ yield 'snsqs' => [[
+ 'default' => [
+ 'transport' => [
+ 'dsn' => getenv('SNSQS_DSN'),
+ ],
+ ],
+ ]];
+
+ //
+ // yield 'gps' => [[
+ // 'transport' => [
+ // 'dsn' => getenv('GPS_DSN'),
+ // ],
+ // ]];
}
/**
@@ -135,7 +167,7 @@ public function testProducerSendsEventMessage(array $enqueueConfig)
$consumer = $this->getContext()->createConsumer($this->getTestQueue());
- $message = $consumer->receive(100);
+ $message = $consumer->receive(self::RECEIVE_TIMEOUT);
$this->assertInstanceOf(Message::class, $message);
$consumer->acknowledge($message);
@@ -155,7 +187,7 @@ public function testProducerSendsCommandMessage(array $enqueueConfig)
$consumer = $this->getContext()->createConsumer($this->getTestQueue());
- $message = $consumer->receive(100);
+ $message = $consumer->receive(self::RECEIVE_TIMEOUT);
$this->assertInstanceOf(Message::class, $message);
$consumer->acknowledge($message);
@@ -166,7 +198,9 @@ public function testProducerSendsCommandMessage(array $enqueueConfig)
public function testProducerSendsEventMessageViaProduceCommand()
{
$this->customSetUp([
- 'transport' => getenv('AMQP_DSN'),
+ 'default' => [
+ 'transport' => getenv('AMQP_DSN'),
+ ],
]);
$expectedBody = __METHOD__.time();
@@ -181,7 +215,7 @@ public function testProducerSendsEventMessageViaProduceCommand()
$consumer = $this->getContext()->createConsumer($this->getTestQueue());
- $message = $consumer->receive(100);
+ $message = $consumer->receive(self::RECEIVE_TIMEOUT);
$this->assertInstanceOf(Message::class, $message);
$consumer->acknowledge($message);
@@ -191,7 +225,9 @@ public function testProducerSendsEventMessageViaProduceCommand()
public function testProducerSendsCommandMessageViaProduceCommand()
{
$this->customSetUp([
- 'transport' => getenv('AMQP_DSN'),
+ 'default' => [
+ 'transport' => getenv('AMQP_DSN'),
+ ],
]);
$expectedBody = __METHOD__.time();
@@ -206,7 +242,7 @@ public function testProducerSendsCommandMessageViaProduceCommand()
$consumer = $this->getContext()->createConsumer($this->getTestQueue());
- $message = $consumer->receive(100);
+ $message = $consumer->receive(self::RECEIVE_TIMEOUT);
$this->assertInstanceOf(Message::class, $message);
$consumer->acknowledge($message);
@@ -217,7 +253,9 @@ public function testProducerSendsCommandMessageViaProduceCommand()
public function testShouldSetupBroker()
{
$this->customSetUp([
- 'transport' => 'file://'.sys_get_temp_dir(),
+ 'default' => [
+ 'transport' => 'file://'.sys_get_temp_dir(),
+ ],
]);
$command = static::$container->get('test_enqueue.client.setup_broker_command');
@@ -230,7 +268,9 @@ public function testShouldSetupBroker()
public function testClientConsumeCommandMessagesFromExplicitlySetQueue()
{
$this->customSetUp([
- 'transport' => getenv('AMQP_DSN'),
+ 'default' => [
+ 'transport' => getenv('AMQP_DSN'),
+ ],
]);
$command = static::$container->get('test_enqueue.client.consume_command');
@@ -255,7 +295,9 @@ public function testClientConsumeCommandMessagesFromExplicitlySetQueue()
public function testClientConsumeMessagesFromExplicitlySetQueue()
{
$this->customSetUp([
- 'transport' => getenv('AMQP_DSN'),
+ 'default' => [
+ 'transport' => getenv('AMQP_DSN'),
+ ],
]);
$expectedBody = __METHOD__.time();
@@ -277,10 +319,12 @@ public function testClientConsumeMessagesFromExplicitlySetQueue()
$this->assertEquals($expectedBody, $processor->message->getBody());
}
- public function testTransportConsumeMessagesCommandShouldConsumeMessage()
+ public function testTransportConsumeCommandShouldConsumeOneMessage()
{
$this->customSetUp([
- 'transport' => getenv('AMQP_DSN'),
+ 'default' => [
+ 'transport' => getenv('AMQP_DSN'),
+ ],
]);
if ($this->getTestQueue() instanceof StompDestination) {
@@ -309,10 +353,7 @@ public function testTransportConsumeMessagesCommandShouldConsumeMessage()
$this->assertEquals($expectedBody, $processor->message->getBody());
}
- /**
- * @return string
- */
- public static function getKernelClass()
+ public static function getKernelClass(): string
{
include_once __DIR__.'/App/CustomAppKernel.php';
@@ -323,9 +364,9 @@ protected function customSetUp(array $enqueueConfig)
{
static::$class = null;
- $this->client = static::createClient(['enqueue_config' => $enqueueConfig]);
- $this->client->getKernel()->boot();
- static::$kernel = $this->client->getKernel();
+ static::$client = static::createClient(['enqueue_config' => $enqueueConfig]);
+ static::$client->getKernel()->boot();
+ static::$kernel = static::$client->getKernel();
static::$container = static::$kernel->getContainer();
/** @var DriverInterface $driver */
diff --git a/pkg/enqueue-bundle/Tests/Functional/WebTestCase.php b/pkg/enqueue-bundle/Tests/Functional/WebTestCase.php
index 0cf1a0723..6a348a9f3 100644
--- a/pkg/enqueue-bundle/Tests/Functional/WebTestCase.php
+++ b/pkg/enqueue-bundle/Tests/Functional/WebTestCase.php
@@ -13,34 +13,33 @@ abstract class WebTestCase extends BaseWebTestCase
/**
* @var Client
*/
- protected $client;
+ protected static $client;
/**
* @var ContainerInterface
*/
protected static $container;
- protected function setUp()
+ protected function setUp(): void
{
parent::setUp();
static::$class = null;
-
- $this->client = static::createClient();
-
- if (false == static::$container) {
- static::$container = static::$kernel->getContainer();
- }
+ static::$client = static::createClient();
+ static::$container = static::$kernel->getContainer();
/** @var TraceableProducer $producer */
$producer = static::$container->get('test_enqueue.client.default.traceable_producer');
$producer->clearTraces();
}
- /**
- * @return string
- */
- public static function getKernelClass()
+ protected function tearDown(): void
+ {
+ static::ensureKernelShutdown();
+ static::$client = null;
+ }
+
+ public static function getKernelClass(): string
{
include_once __DIR__.'/App/AppKernel.php';
diff --git a/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/DoctrineClearIdentityMapExtensionTest.php b/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/DoctrineClearIdentityMapExtensionTest.php
index 518b40f2d..7c5c2dd5d 100644
--- a/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/DoctrineClearIdentityMapExtensionTest.php
+++ b/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/DoctrineClearIdentityMapExtensionTest.php
@@ -2,24 +2,20 @@
namespace Enqueue\Bundle\Tests\Unit\Consumption\Extension;
-use Doctrine\Common\Persistence\ObjectManager;
+use Doctrine\Persistence\ManagerRegistry;
+use Doctrine\Persistence\ObjectManager;
use Enqueue\Bundle\Consumption\Extension\DoctrineClearIdentityMapExtension;
use Enqueue\Consumption\Context\MessageReceived;
use Interop\Queue\Consumer;
use Interop\Queue\Context as InteropContext;
use Interop\Queue\Message;
use Interop\Queue\Processor;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
-use Symfony\Bridge\Doctrine\RegistryInterface;
class DoctrineClearIdentityMapExtensionTest extends TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new DoctrineClearIdentityMapExtension($this->createRegistryMock());
- }
-
public function testShouldClearIdentityMap()
{
$manager = $this->createManagerMock();
@@ -32,7 +28,7 @@ public function testShouldClearIdentityMap()
$registry
->expects($this->once())
->method('getManagers')
- ->will($this->returnValue(['manager-name' => $manager]))
+ ->willReturn(['manager-name' => $manager])
;
$context = $this->createContext();
@@ -59,15 +55,15 @@ protected function createContext(): MessageReceived
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|RegistryInterface
+ * @return MockObject|ManagerRegistry
*/
- protected function createRegistryMock(): RegistryInterface
+ protected function createRegistryMock(): ManagerRegistry
{
- return $this->createMock(RegistryInterface::class);
+ return $this->createMock(ManagerRegistry::class);
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ObjectManager
+ * @return MockObject|ObjectManager
*/
protected function createManagerMock(): ObjectManager
{
diff --git a/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/DoctrineClosedEntityManagerExtensionTest.php b/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/DoctrineClosedEntityManagerExtensionTest.php
new file mode 100644
index 000000000..8e7120325
--- /dev/null
+++ b/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/DoctrineClosedEntityManagerExtensionTest.php
@@ -0,0 +1,223 @@
+createManagerMock(true);
+
+ $registry = $this->createRegistryMock([
+ 'manager' => $manager,
+ ]);
+
+ $message = new PreConsume(
+ $this->createMock(InteropContext::class),
+ $this->createMock(SubscriptionConsumer::class),
+ $this->createMock(LoggerInterface::class),
+ 1,
+ 2,
+ 3
+ );
+
+ self::assertFalse($message->isExecutionInterrupted());
+
+ $extension = new DoctrineClosedEntityManagerExtension($registry);
+ $extension->onPreConsume($message);
+
+ self::assertFalse($message->isExecutionInterrupted());
+ }
+
+ public function testOnPreConsumeShouldInterruptExecutionIfAManagerIsClosed()
+ {
+ $manager1 = $this->createManagerMock(true);
+ $manager2 = $this->createManagerMock(false);
+
+ $registry = $this->createRegistryMock([
+ 'manager1' => $manager1,
+ 'manager2' => $manager2,
+ ]);
+
+ $message = new PreConsume(
+ $this->createMock(InteropContext::class),
+ $this->createMock(SubscriptionConsumer::class),
+ $this->createMock(LoggerInterface::class),
+ 1,
+ 2,
+ 3
+ );
+ $message->getLogger()
+ ->expects($this->once())
+ ->method('debug')
+ ->with('[DoctrineClosedEntityManagerExtension] Interrupt execution as entity manager "manager2" has been closed')
+ ;
+
+ self::assertFalse($message->isExecutionInterrupted());
+
+ $extension = new DoctrineClosedEntityManagerExtension($registry);
+ $extension->onPreConsume($message);
+
+ self::assertTrue($message->isExecutionInterrupted());
+ }
+
+ public function testOnPostConsumeShouldNotInterruptExecution()
+ {
+ $manager = $this->createManagerMock(true);
+
+ $registry = $this->createRegistryMock([
+ 'manager' => $manager,
+ ]);
+
+ $message = new PostConsume(
+ $this->createMock(InteropContext::class),
+ $this->createMock(SubscriptionConsumer::class),
+ 1,
+ 1,
+ 1,
+ $this->createMock(LoggerInterface::class)
+ );
+
+ self::assertFalse($message->isExecutionInterrupted());
+
+ $extension = new DoctrineClosedEntityManagerExtension($registry);
+ $extension->onPostConsume($message);
+
+ self::assertFalse($message->isExecutionInterrupted());
+ }
+
+ public function testOnPostConsumeShouldInterruptExecutionIfAManagerIsClosed()
+ {
+ $manager1 = $this->createManagerMock(true);
+ $manager2 = $this->createManagerMock(false);
+
+ $registry = $this->createRegistryMock([
+ 'manager1' => $manager1,
+ 'manager2' => $manager2,
+ ]);
+
+ $message = new PostConsume(
+ $this->createMock(InteropContext::class),
+ $this->createMock(SubscriptionConsumer::class),
+ 1,
+ 1,
+ 1,
+ $this->createMock(LoggerInterface::class)
+ );
+ $message->getLogger()
+ ->expects($this->once())
+ ->method('debug')
+ ->with('[DoctrineClosedEntityManagerExtension] Interrupt execution as entity manager "manager2" has been closed')
+ ;
+
+ self::assertFalse($message->isExecutionInterrupted());
+
+ $extension = new DoctrineClosedEntityManagerExtension($registry);
+ $extension->onPostConsume($message);
+
+ self::assertTrue($message->isExecutionInterrupted());
+ }
+
+ public function testOnPostReceivedShouldNotInterruptExecution()
+ {
+ $manager = $this->createManagerMock(true);
+
+ $registry = $this->createRegistryMock([
+ 'manager' => $manager,
+ ]);
+
+ $message = new PostMessageReceived(
+ $this->createMock(InteropContext::class),
+ $this->createMock(Consumer::class),
+ $this->createMock(Message::class),
+ 'aResult',
+ 1,
+ $this->createMock(LoggerInterface::class)
+ );
+
+ self::assertFalse($message->isExecutionInterrupted());
+
+ $extension = new DoctrineClosedEntityManagerExtension($registry);
+ $extension->onPostMessageReceived($message);
+
+ self::assertFalse($message->isExecutionInterrupted());
+ }
+
+ public function testOnPostReceivedShouldInterruptExecutionIfAManagerIsClosed()
+ {
+ $manager1 = $this->createManagerMock(true);
+ $manager2 = $this->createManagerMock(false);
+
+ $registry = $this->createRegistryMock([
+ 'manager1' => $manager1,
+ 'manager2' => $manager2,
+ ]);
+
+ $message = new PostMessageReceived(
+ $this->createMock(InteropContext::class),
+ $this->createMock(Consumer::class),
+ $this->createMock(Message::class),
+ 'aResult',
+ 1,
+ $this->createMock(LoggerInterface::class)
+ );
+ $message->getLogger()
+ ->expects($this->once())
+ ->method('debug')
+ ->with('[DoctrineClosedEntityManagerExtension] Interrupt execution as entity manager "manager2" has been closed')
+ ;
+
+ self::assertFalse($message->isExecutionInterrupted());
+
+ $extension = new DoctrineClosedEntityManagerExtension($registry);
+ $extension->onPostMessageReceived($message);
+
+ self::assertTrue($message->isExecutionInterrupted());
+ }
+
+ /**
+ * @return MockObject|ManagerRegistry
+ */
+ protected function createRegistryMock(array $managers): ManagerRegistry
+ {
+ $mock = $this->createMock(ManagerRegistry::class);
+
+ $mock
+ ->expects($this->once())
+ ->method('getManagers')
+ ->willReturn($managers)
+ ;
+
+ return $mock;
+ }
+
+ /**
+ * @return MockObject|EntityManagerInterface
+ */
+ protected function createManagerMock(bool $open): EntityManagerInterface
+ {
+ $mock = $this->createMock(EntityManagerInterface::class);
+
+ $mock
+ ->expects($this->once())
+ ->method('isOpen')
+ ->willReturn($open)
+ ;
+
+ return $mock;
+ }
+}
diff --git a/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/DoctrinePingConnectionExtensionTest.php b/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/DoctrinePingConnectionExtensionTest.php
index d7f16dd57..b690fa290 100644
--- a/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/DoctrinePingConnectionExtensionTest.php
+++ b/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/DoctrinePingConnectionExtensionTest.php
@@ -3,60 +3,73 @@
namespace Enqueue\Bundle\Tests\Unit\Consumption\Extension;
use Doctrine\DBAL\Connection;
+use Doctrine\DBAL\Platforms\AbstractPlatform;
+use Doctrine\Persistence\ManagerRegistry;
use Enqueue\Bundle\Consumption\Extension\DoctrinePingConnectionExtension;
use Enqueue\Consumption\Context\MessageReceived;
+use Enqueue\Test\TestLogger;
use Interop\Queue\Consumer;
use Interop\Queue\Context as InteropContext;
use Interop\Queue\Message;
use Interop\Queue\Processor;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
-use Psr\Log\LoggerInterface;
-use Symfony\Bridge\Doctrine\RegistryInterface;
class DoctrinePingConnectionExtensionTest extends TestCase
{
- public function testCouldBeConstructedWithRequiredAttributes()
- {
- new DoctrinePingConnectionExtension($this->createRegistryMock());
- }
-
public function testShouldNotReconnectIfConnectionIsOK()
{
$connection = $this->createConnectionMock();
$connection
->expects($this->once())
->method('isConnected')
- ->will($this->returnValue(true))
+ ->willReturn(true)
;
+
+ $abstractPlatform = $this->createMock(AbstractPlatform::class);
+ $abstractPlatform->expects($this->once())
+ ->method('getDummySelectSQL')
+ ->willReturn('dummy')
+ ;
+
$connection
->expects($this->once())
- ->method('ping')
- ->will($this->returnValue(true))
+ ->method('getDatabasePlatform')
+ ->willReturn($abstractPlatform)
;
$connection
->expects($this->never())
->method('close')
;
- $connection
- ->expects($this->never())
- ->method('connect')
- ;
+ if (
+ method_exists(Connection::class, 'connect')
+ && (new \ReflectionMethod(Connection::class, 'connect'))->isPublic()
+ ) {
+ // DBAL < 4
+ $connection->expects($this->never())
+ ->method('connect');
+ } else {
+ // DBAL >= 4, calls connect() internally
+ $connection
+ ->expects($this->never())
+ ->method('getServerVersion');
+ }
$context = $this->createContext();
- $context->getLogger()
- ->expects($this->never())
- ->method('debug')
- ;
$registry = $this->createRegistryMock();
$registry
- ->expects($this->once())
+ ->expects(self::once())
->method('getConnections')
- ->will($this->returnValue([$connection]))
+ ->willReturn([$connection])
;
$extension = new DoctrinePingConnectionExtension($registry);
$extension->onMessageReceived($context);
+
+ /** @var TestLogger $logger */
+ $logger = $context->getLogger();
+ self::assertFalse($logger->hasDebugRecords());
}
public function testShouldDoesReconnectIfConnectionFailed()
@@ -65,43 +78,55 @@ public function testShouldDoesReconnectIfConnectionFailed()
$connection
->expects($this->once())
->method('isConnected')
- ->will($this->returnValue(true))
+ ->willReturn(true)
;
+
$connection
->expects($this->once())
- ->method('ping')
- ->will($this->returnValue(false))
+ ->method('getDatabasePlatform')
+ ->willThrowException(new \Exception())
;
$connection
->expects($this->once())
->method('close')
;
- $connection
- ->expects($this->once())
- ->method('connect')
- ;
+ if (
+ method_exists(Connection::class, 'connect')
+ && (new \ReflectionMethod(Connection::class, 'connect'))->isPublic()
+ ) {
+ // DBAL < 4
+ $connection->expects($this->once())
+ ->method('connect');
+ } else {
+ // DBAL >= 4, calls connect() internally
+ $connection->expects($this->once())
+ ->method('getServerVersion');
+ }
$context = $this->createContext();
- $context->getLogger()
- ->expects($this->at(0))
- ->method('debug')
- ->with('[DoctrinePingConnectionExtension] Connection is not active trying to reconnect.')
- ;
- $context->getLogger()
- ->expects($this->at(1))
- ->method('debug')
- ->with('[DoctrinePingConnectionExtension] Connection is active now.')
- ;
$registry = $this->createRegistryMock();
$registry
->expects($this->once())
->method('getConnections')
- ->will($this->returnValue([$connection]))
+ ->willReturn([$connection])
;
$extension = new DoctrinePingConnectionExtension($registry);
$extension->onMessageReceived($context);
+
+ /** @var TestLogger $logger */
+ $logger = $context->getLogger();
+ self::assertTrue(
+ $logger->hasDebugThatContains(
+ '[DoctrinePingConnectionExtension] Connection is not active trying to reconnect.'
+ )
+ );
+ self::assertTrue(
+ $logger->hasDebugThatContains(
+ '[DoctrinePingConnectionExtension] Connection is active now.'
+ )
+ );
}
public function testShouldSkipIfConnectionWasNotOpened()
@@ -110,11 +135,11 @@ public function testShouldSkipIfConnectionWasNotOpened()
$connection1
->expects($this->once())
->method('isConnected')
- ->will($this->returnValue(false))
+ ->willReturn(false)
;
$connection1
->expects($this->never())
- ->method('ping')
+ ->method('getDatabasePlatform')
;
// 2nd connection was opened in the past
@@ -122,29 +147,35 @@ public function testShouldSkipIfConnectionWasNotOpened()
$connection2
->expects($this->once())
->method('isConnected')
- ->will($this->returnValue(true))
+ ->willReturn(true)
+ ;
+ $abstractPlatform = $this->createMock(AbstractPlatform::class);
+ $abstractPlatform->expects($this->once())
+ ->method('getDummySelectSQL')
+ ->willReturn('dummy')
;
+
$connection2
->expects($this->once())
- ->method('ping')
- ->will($this->returnValue(true))
+ ->method('getDatabasePlatform')
+ ->willReturn($abstractPlatform)
;
$context = $this->createContext();
- $context->getLogger()
- ->expects($this->never())
- ->method('debug')
- ;
$registry = $this->createRegistryMock();
$registry
->expects($this->once())
->method('getConnections')
- ->will($this->returnValue([$connection1, $connection2]))
+ ->willReturn([$connection1, $connection2])
;
$extension = new DoctrinePingConnectionExtension($registry);
$extension->onMessageReceived($context);
+
+ /** @var TestLogger $logger */
+ $logger = $context->getLogger();
+ $this->assertFalse($logger->hasDebugRecords());
}
protected function createContext(): MessageReceived
@@ -155,20 +186,20 @@ protected function createContext(): MessageReceived
$this->createMock(Message::class),
$this->createMock(Processor::class),
1,
- $this->createMock(LoggerInterface::class)
+ new TestLogger()
);
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|RegistryInterface
+ * @return MockObject|ManagerRegistry
*/
- protected function createRegistryMock(): RegistryInterface
+ protected function createRegistryMock()
{
- return $this->createMock(RegistryInterface::class);
+ return $this->createMock(ManagerRegistry::class);
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Connection
+ * @return MockObject|Connection
*/
protected function createConnectionMock(): Connection
{
diff --git a/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/ResetServicesExtensionTest.php b/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/ResetServicesExtensionTest.php
new file mode 100644
index 000000000..e0d96fafa
--- /dev/null
+++ b/pkg/enqueue-bundle/Tests/Unit/Consumption/Extension/ResetServicesExtensionTest.php
@@ -0,0 +1,57 @@
+createResetterMock();
+ $resetter
+ ->expects($this->once())
+ ->method('reset')
+ ;
+
+ $context = $this->createContext();
+ $context->getLogger()
+ ->expects($this->once())
+ ->method('debug')
+ ->with('[ResetServicesExtension] Resetting services.')
+ ;
+
+ $extension = new ResetServicesExtension($resetter);
+ $extension->onPostMessageReceived($context);
+ }
+
+ protected function createContext(): PostMessageReceived
+ {
+ return new PostMessageReceived(
+ $this->createMock(InteropContext::class),
+ $this->createMock(Consumer::class),
+ $this->createMock(Message::class),
+ $this->createMock(Processor::class),
+ 1,
+ $this->createMock(LoggerInterface::class)
+ );
+ }
+
+ /**
+ * @return MockObject|ManagerRegistry
+ */
+ protected function createResetterMock(): ResetInterface
+ {
+ return $this->createMock(ResetInterface::class);
+ }
+}
diff --git a/pkg/enqueue-bundle/Tests/Unit/DependencyInjection/ConfigurationTest.php b/pkg/enqueue-bundle/Tests/Unit/DependencyInjection/ConfigurationTest.php
index 823a2ac13..5330cde82 100644
--- a/pkg/enqueue-bundle/Tests/Unit/DependencyInjection/ConfigurationTest.php
+++ b/pkg/enqueue-bundle/Tests/Unit/DependencyInjection/ConfigurationTest.php
@@ -2,12 +2,13 @@
namespace Enqueue\Bundle\Tests\Unit\DependencyInjection;
+use DMS\PHPUnitExtensions\ArraySubset\Assert;
use Enqueue\Bundle\DependencyInjection\Configuration;
-use Enqueue\Client\RouterProcessor;
use Enqueue\Test\ClassExtensionTrait;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
+use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
use Symfony\Component\Config\Definition\Processor;
class ConfigurationTest extends TestCase
@@ -24,82 +25,134 @@ public function testShouldBeFinal()
$this->assertClassFinal(Configuration::class);
}
- public function testCouldBeConstructedWithDebugAsArgument()
+ public function testShouldProcessSeveralTransports()
{
- new Configuration(true);
+ $configuration = new Configuration(true);
+
+ $processor = new Processor();
+ $config = $processor->processConfiguration($configuration, [[
+ 'default' => [
+ 'transport' => 'default:',
+ ],
+ 'foo' => [
+ 'transport' => 'foo:',
+ ],
+ ]]);
+
+ $this->assertConfigEquals([
+ 'default' => [
+ 'transport' => [
+ 'dsn' => 'default:',
+ ],
+ ],
+ 'foo' => [
+ 'transport' => [
+ 'dsn' => 'foo:',
+ ],
+ ],
+ ], $config);
}
- public function testShouldUseDefaultConfigurationIfNothingIsConfiguredAtAll()
+ public function testTransportFactoryShouldValidateEachTransportAccordingToItsRules()
{
$configuration = new Configuration(true);
$processor = new Processor();
- $config = $processor->processConfiguration($configuration, [[]]);
-
- $this->assertEquals([
- 'transport' => ['dsn' => 'null:'],
- 'consumption' => [
- 'receive_timeout' => 10000,
- ],
- 'job' => false,
- 'async_events' => ['enabled' => false],
- 'async_commands' => ['enabled' => false],
- 'extensions' => [
- 'doctrine_ping_connection_extension' => false,
- 'doctrine_clear_identity_map_extension' => false,
- 'signal_extension' => function_exists('pcntl_signal_dispatch'),
- 'reply_extension' => true,
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Both options factory_class and factory_service are set. Please choose one.');
+ $processor->processConfiguration($configuration, [
+ [
+ 'default' => [
+ 'transport' => [
+ 'factory_class' => 'aClass',
+ 'factory_service' => 'aService',
+ ],
+ ],
],
- ], $config);
+ ]);
}
- public function testShouldUseDefaultTransportIfIfTransportIsConfiguredAtAll()
+ public function testShouldSetDefaultConfigurationForClient()
{
$configuration = new Configuration(true);
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => null,
+ 'default' => [
+ 'transport' => 'null:',
+ 'client' => null,
+ ],
]]);
- $this->assertEquals([
- 'transport' => ['dsn' => 'null:'],
- 'consumption' => [
- 'receive_timeout' => 10000,
- ],
- 'job' => false,
- 'async_events' => ['enabled' => false],
- 'async_commands' => ['enabled' => false],
- 'extensions' => [
- 'doctrine_ping_connection_extension' => false,
- 'doctrine_clear_identity_map_extension' => false,
- 'signal_extension' => function_exists('pcntl_signal_dispatch'),
- 'reply_extension' => true,
+ $this->assertConfigEquals([
+ 'default' => [
+ 'client' => [
+ 'prefix' => 'enqueue',
+ 'app_name' => 'app',
+ 'router_processor' => null,
+ 'router_topic' => 'default',
+ 'router_queue' => 'default',
+ 'default_queue' => 'default',
+ 'traceable_producer' => true,
+ 'redelivered_delay_time' => 0,
+ ],
],
], $config);
}
- public function testShouldSetDefaultConfigurationForClient()
+ public function testThrowIfClientDriverOptionsIsNotArray()
+ {
+ $configuration = new Configuration(true);
+
+ $processor = new Processor();
+
+ $this->expectException(InvalidTypeException::class);
+ // Exception messages vary slightly between versions
+ $this->expectExceptionMessageMatches(
+ '/Invalid type for path "enqueue\.default\.client\.driver_options"\. Expected "?array"?, but got "?string"?/'
+ );
+
+ $processor->processConfiguration($configuration, [[
+ 'default' => [
+ 'transport' => 'null:',
+ 'client' => [
+ 'driver_options' => 'invalidOption',
+ ],
+ ],
+ ]]);
+ }
+
+ public function testShouldConfigureClientDriverOptions()
{
$configuration = new Configuration(true);
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => 'null:',
- 'client' => null,
+ 'default' => [
+ 'transport' => 'null:',
+ 'client' => [
+ 'driver_options' => [
+ 'foo' => 'fooVal',
+ ],
+ ],
+ ],
]]);
- $this->assertArraySubset([
- 'transport' => ['dsn' => 'null:'],
- 'client' => [
- 'prefix' => 'enqueue',
- 'app_name' => 'app',
- 'router_processor' => RouterProcessor::class,
- 'router_topic' => 'default',
- 'router_queue' => 'default',
- 'default_processor_queue' => 'default',
- 'traceable_producer' => true,
- 'redelivered_delay_time' => 0,
+ $this->assertConfigEquals([
+ 'default' => [
+ 'client' => [
+ 'prefix' => 'enqueue',
+ 'app_name' => 'app',
+ 'router_processor' => null,
+ 'router_topic' => 'default',
+ 'router_queue' => 'default',
+ 'default_queue' => 'default',
+ 'traceable_producer' => true,
+ 'driver_options' => [
+ 'foo' => 'fooVal',
+ ],
+ ],
],
], $config);
}
@@ -107,15 +160,17 @@ public function testShouldSetDefaultConfigurationForClient()
public function testThrowExceptionIfRouterTopicIsEmpty()
{
$this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessage('The path "enqueue.client.router_topic" cannot contain an empty value, but got "".');
+ $this->expectExceptionMessage('The path "enqueue.default.client.router_topic" cannot contain an empty value, but got "".');
$configuration = new Configuration(true);
$processor = new Processor();
$processor->processConfiguration($configuration, [[
- 'transport' => ['dsn' => 'null:'],
- 'client' => [
- 'router_topic' => '',
+ 'default' => [
+ 'transport' => ['dsn' => 'null:'],
+ 'client' => [
+ 'router_topic' => '',
+ ],
],
]]);
}
@@ -123,15 +178,17 @@ public function testThrowExceptionIfRouterTopicIsEmpty()
public function testThrowExceptionIfRouterQueueIsEmpty()
{
$this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessage('The path "enqueue.client.router_queue" cannot contain an empty value, but got "".');
+ $this->expectExceptionMessage('The path "enqueue.default.client.router_queue" cannot contain an empty value, but got "".');
$configuration = new Configuration(true);
$processor = new Processor();
$processor->processConfiguration($configuration, [[
- 'transport' => ['dsn' => 'null:'],
- 'client' => [
- 'router_queue' => '',
+ 'default' => [
+ 'transport' => ['dsn' => 'null:'],
+ 'client' => [
+ 'router_queue' => '',
+ ],
],
]]);
}
@@ -143,11 +200,13 @@ public function testShouldThrowExceptionIfDefaultProcessorQueueIsEmpty()
$processor = new Processor();
$this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessage('The path "enqueue.client.default_processor_queue" cannot contain an empty value, but got "".');
+ $this->expectExceptionMessage('The path "enqueue.default.client.default_queue" cannot contain an empty value, but got "".');
$processor->processConfiguration($configuration, [[
- 'transport' => ['dsn' => 'null:'],
- 'client' => [
- 'default_processor_queue' => '',
+ 'default' => [
+ 'transport' => ['dsn' => 'null:'],
+ 'client' => [
+ 'default_queue' => '',
+ ],
],
]]);
}
@@ -158,11 +217,17 @@ public function testJobShouldBeDisabledByDefault()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
+ 'default' => [
+ 'transport' => [],
+ ],
]]);
- $this->assertArraySubset([
- 'job' => false,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'job' => [
+ 'enabled' => false,
+ ],
+ ],
], $config);
}
@@ -172,12 +237,16 @@ public function testCouldEnableJob()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
- 'job' => true,
+ 'default' => [
+ 'transport' => [],
+ 'job' => true,
+ ],
]]);
- $this->assertArraySubset([
- 'job' => true,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'job' => true,
+ ],
], $config);
}
@@ -187,12 +256,16 @@ public function testDoctrinePingConnectionExtensionShouldBeDisabledByDefault()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
+ 'default' => [
+ 'transport' => null,
+ ],
]]);
- $this->assertArraySubset([
- 'extensions' => [
- 'doctrine_ping_connection_extension' => false,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'doctrine_ping_connection_extension' => false,
+ ],
],
], $config);
}
@@ -203,15 +276,19 @@ public function testDoctrinePingConnectionExtensionCouldBeEnabled()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
- 'extensions' => [
- 'doctrine_ping_connection_extension' => true,
+ 'default' => [
+ 'transport' => null,
+ 'extensions' => [
+ 'doctrine_ping_connection_extension' => true,
+ ],
],
]]);
- $this->assertArraySubset([
- 'extensions' => [
- 'doctrine_ping_connection_extension' => true,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'doctrine_ping_connection_extension' => true,
+ ],
],
], $config);
}
@@ -222,12 +299,16 @@ public function testDoctrineClearIdentityMapExtensionShouldBeDisabledByDefault()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
+ 'default' => [
+ 'transport' => null,
+ ],
]]);
- $this->assertArraySubset([
- 'extensions' => [
- 'doctrine_clear_identity_map_extension' => false,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'doctrine_clear_identity_map_extension' => false,
+ ],
],
], $config);
}
@@ -238,15 +319,148 @@ public function testDoctrineClearIdentityMapExtensionCouldBeEnabled()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
- 'extensions' => [
- 'doctrine_clear_identity_map_extension' => true,
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'doctrine_clear_identity_map_extension' => true,
+ ],
],
]]);
- $this->assertArraySubset([
- 'extensions' => [
- 'doctrine_clear_identity_map_extension' => true,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'doctrine_clear_identity_map_extension' => true,
+ ],
+ ],
+ ], $config);
+ }
+
+ public function testDoctrineOdmClearIdentityMapExtensionShouldBeDisabledByDefault()
+ {
+ $configuration = new Configuration(true);
+
+ $processor = new Processor();
+ $config = $processor->processConfiguration($configuration, [[
+ 'default' => [
+ 'transport' => null,
+ ],
+ ]]);
+
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'doctrine_odm_clear_identity_map_extension' => false,
+ ],
+ ],
+ ], $config);
+ }
+
+ public function testDoctrineOdmClearIdentityMapExtensionCouldBeEnabled()
+ {
+ $configuration = new Configuration(true);
+
+ $processor = new Processor();
+ $config = $processor->processConfiguration($configuration, [[
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'doctrine_odm_clear_identity_map_extension' => true,
+ ],
+ ],
+ ]]);
+
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'doctrine_odm_clear_identity_map_extension' => true,
+ ],
+ ],
+ ], $config);
+ }
+
+ public function testDoctrineClosedEntityManagerExtensionShouldBeDisabledByDefault()
+ {
+ $configuration = new Configuration(true);
+
+ $processor = new Processor();
+ $config = $processor->processConfiguration($configuration, [[
+ 'default' => [
+ 'transport' => null,
+ ],
+ ]]);
+
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'doctrine_closed_entity_manager_extension' => false,
+ ],
+ ],
+ ], $config);
+ }
+
+ public function testDoctrineClosedEntityManagerExtensionCouldBeEnabled()
+ {
+ $configuration = new Configuration(true);
+
+ $processor = new Processor();
+ $config = $processor->processConfiguration($configuration, [[
+ 'default' => [
+ 'transport' => null,
+ 'extensions' => [
+ 'doctrine_closed_entity_manager_extension' => true,
+ ],
+ ],
+ ]]);
+
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'doctrine_closed_entity_manager_extension' => true,
+ ],
+ ],
+ ], $config);
+ }
+
+ public function testResetServicesExtensionShouldBeDisabledByDefault()
+ {
+ $configuration = new Configuration(true);
+
+ $processor = new Processor();
+ $config = $processor->processConfiguration($configuration, [[
+ 'default' => [
+ 'transport' => null,
+ ],
+ ]]);
+
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'reset_services_extension' => false,
+ ],
+ ],
+ ], $config);
+ }
+
+ public function testResetServicesExtensionCouldBeEnabled()
+ {
+ $configuration = new Configuration(true);
+
+ $processor = new Processor();
+ $config = $processor->processConfiguration($configuration, [[
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'reset_services_extension' => true,
+ ],
+ ],
+ ]]);
+
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'reset_services_extension' => true,
+ ],
],
], $config);
}
@@ -259,12 +473,16 @@ public function testSignalExtensionShouldBeEnabledIfPcntlExtensionIsLoaded()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
+ 'default' => [
+ 'transport' => [],
+ ],
]]);
- $this->assertArraySubset([
- 'extensions' => [
- 'signal_extension' => $isLoaded,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'signal_extension' => $isLoaded,
+ ],
],
], $config);
}
@@ -275,15 +493,19 @@ public function testSignalExtensionCouldBeDisabled()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
- 'extensions' => [
- 'signal_extension' => false,
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'signal_extension' => false,
+ ],
],
]]);
- $this->assertArraySubset([
- 'extensions' => [
- 'signal_extension' => false,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'signal_extension' => false,
+ ],
],
], $config);
}
@@ -294,12 +516,16 @@ public function testReplyExtensionShouldBeEnabledByDefault()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
+ 'default' => [
+ 'transport' => [],
+ ],
]]);
- $this->assertArraySubset([
- 'extensions' => [
- 'reply_extension' => true,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'reply_extension' => true,
+ ],
],
], $config);
}
@@ -310,15 +536,19 @@ public function testReplyExtensionCouldBeDisabled()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
- 'extensions' => [
- 'reply_extension' => false,
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'reply_extension' => false,
+ ],
],
]]);
- $this->assertArraySubset([
- 'extensions' => [
- 'reply_extension' => false,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'extensions' => [
+ 'reply_extension' => false,
+ ],
],
], $config);
}
@@ -329,12 +559,16 @@ public function testShouldDisableAsyncEventsByDefault()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
+ 'default' => [
+ 'transport' => [],
+ ],
]]);
- $this->assertArraySubset([
- 'async_events' => [
- 'enabled' => false,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'async_events' => [
+ 'enabled' => false,
+ ],
],
], $config);
}
@@ -346,26 +580,34 @@ public function testShouldAllowEnableAsyncEvents()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
- 'async_events' => true,
+ 'default' => [
+ 'transport' => [],
+ 'async_events' => true,
+ ],
]]);
- $this->assertArraySubset([
- 'async_events' => [
- 'enabled' => true,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'async_events' => [
+ 'enabled' => true,
+ ],
],
], $config);
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
- 'async_events' => [
- 'enabled' => true,
+ 'default' => [
+ 'transport' => [],
+ 'async_events' => [
+ 'enabled' => true,
+ ],
],
]]);
- $this->assertArraySubset([
- 'async_events' => [
- 'enabled' => true,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'async_events' => [
+ 'enabled' => true,
+ ],
],
], $config);
}
@@ -376,12 +618,16 @@ public function testShouldSetDefaultConfigurationForConsumption()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
+ 'default' => [
+ 'transport' => [],
+ ],
]]);
- $this->assertArraySubset([
- 'consumption' => [
- 'receive_timeout' => 10000,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'consumption' => [
+ 'receive_timeout' => 10000,
+ ],
],
], $config);
}
@@ -392,16 +638,25 @@ public function testShouldAllowConfigureConsumption()
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
- 'transport' => [],
- 'consumption' => [
- 'receive_timeout' => 456,
+ 'default' => [
+ 'transport' => [],
+ 'consumption' => [
+ 'receive_timeout' => 456,
+ ],
],
]]);
- $this->assertArraySubset([
- 'consumption' => [
- 'receive_timeout' => 456,
+ Assert::assertArraySubset([
+ 'default' => [
+ 'consumption' => [
+ 'receive_timeout' => 456,
+ ],
],
], $config);
}
+
+ private function assertConfigEquals(array $expected, array $actual): void
+ {
+ Assert::assertArraySubset($expected, $actual, false, var_export($actual, true));
+ }
}
diff --git a/pkg/enqueue-bundle/Tests/Unit/DependencyInjection/EnqueueExtensionTest.php b/pkg/enqueue-bundle/Tests/Unit/DependencyInjection/EnqueueExtensionTest.php
index 8b4ebf7b2..6358bd24d 100644
--- a/pkg/enqueue-bundle/Tests/Unit/DependencyInjection/EnqueueExtensionTest.php
+++ b/pkg/enqueue-bundle/Tests/Unit/DependencyInjection/EnqueueExtensionTest.php
@@ -13,8 +13,8 @@
use Enqueue\Test\ClassExtensionTrait;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
+use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Reference;
-use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class EnqueueExtensionTest extends TestCase
{
@@ -22,17 +22,12 @@ class EnqueueExtensionTest extends TestCase
public function testShouldImplementConfigurationInterface()
{
- self::assertClassExtends(Extension::class, EnqueueExtension::class);
+ $this->assertClassExtends(Extension::class, EnqueueExtension::class);
}
public function testShouldBeFinal()
{
- self::assertClassFinal(EnqueueExtension::class);
- }
-
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new EnqueueExtension();
+ $this->assertClassFinal(EnqueueExtension::class);
}
public function testShouldRegisterConnectionFactory()
@@ -41,7 +36,11 @@ public function testShouldRegisterConnectionFactory()
$extension = new EnqueueExtension();
- $extension->load([[]], $container);
+ $extension->load([[
+ 'default' => [
+ 'transport' => null,
+ ],
+ ]], $container);
self::assertTrue($container->hasDefinition('enqueue.transport.default.connection_factory'));
self::assertNotEmpty($container->getDefinition('enqueue.transport.default.connection_factory')->getFactory());
@@ -53,7 +52,11 @@ public function testShouldRegisterContext()
$extension = new EnqueueExtension();
- $extension->load([[]], $container);
+ $extension->load([[
+ 'default' => [
+ 'transport' => null,
+ ],
+ ]], $container);
self::assertTrue($container->hasDefinition('enqueue.transport.default.context'));
self::assertNotEmpty($container->getDefinition('enqueue.transport.default.context')->getFactory());
@@ -66,8 +69,10 @@ public function testShouldRegisterClientDriver()
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => null,
- 'client' => true,
+ 'default' => [
+ 'transport' => null,
+ 'client' => true,
+ ],
]], $container);
self::assertTrue($container->hasDefinition('enqueue.client.default.driver'));
@@ -81,8 +86,10 @@ public function testShouldLoadClientServicesWhenEnabled()
$extension = new EnqueueExtension();
$extension->load([[
- 'client' => null,
- 'transport' => 'null:',
+ 'default' => [
+ 'client' => null,
+ 'transport' => 'null:',
+ ],
]], $container);
self::assertTrue($container->hasDefinition('enqueue.client.default.driver'));
@@ -97,8 +104,10 @@ public function testShouldUseProducerByDefault()
$extension = new EnqueueExtension();
$extension->load([[
- 'client' => null,
- 'transport' => 'null',
+ 'default' => [
+ 'client' => null,
+ 'transport' => 'null',
+ ],
]], $container);
$producer = $container->getDefinition('enqueue.client.default.producer');
@@ -112,10 +121,12 @@ public function testShouldUseMessageProducerIfTraceableProducerOptionSetToFalseE
$extension = new EnqueueExtension();
$extension->load([[
- 'client' => [
- 'traceable_producer' => false,
+ 'default' => [
+ 'client' => [
+ 'traceable_producer' => false,
+ ],
+ 'transport' => 'null:',
],
- 'transport' => 'null:',
]], $container);
$producer = $container->getDefinition('enqueue.client.default.producer');
@@ -129,8 +140,10 @@ public function testShouldUseTraceableMessageProducerIfDebugEnabled()
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => 'null:',
- 'client' => null,
+ 'default' => [
+ 'transport' => 'null:',
+ 'client' => null,
+ ],
]], $container);
$producer = $container->getDefinition('enqueue.client.default.traceable_producer');
@@ -157,7 +170,9 @@ public function testShouldNotUseTraceableMessageProducerIfDebugDisabledAndNotSet
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => 'null:',
+ 'default' => [
+ 'transport' => 'null:',
+ ],
]], $container);
$this->assertFalse($container->hasDefinition('enqueue.client.default.traceable_producer'));
@@ -170,10 +185,12 @@ public function testShouldUseTraceableMessageProducerIfDebugDisabledButTraceable
$extension = new EnqueueExtension();
$extension->load([[
- 'client' => [
- 'traceable_producer' => true,
+ 'default' => [
+ 'client' => [
+ 'traceable_producer' => true,
+ ],
+ 'transport' => 'null:',
],
- 'transport' => 'null:',
]], $container);
$producer = $container->getDefinition('enqueue.client.default.traceable_producer');
@@ -200,9 +217,11 @@ public function testShouldLoadDelayRedeliveredMessageExtensionIfRedeliveredDelay
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => 'null:',
- 'client' => [
- 'redelivered_delay_time' => 12345,
+ 'default' => [
+ 'transport' => 'null:',
+ 'client' => [
+ 'redelivered_delay_time' => 12345,
+ ],
],
]], $container);
@@ -218,9 +237,11 @@ public function testShouldNotLoadDelayRedeliveredMessageExtensionIfRedeliveredDe
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => 'null:',
- 'client' => [
- 'redelivered_delay_time' => 0,
+ 'default' => [
+ 'transport' => 'null:',
+ 'client' => [
+ 'redelivered_delay_time' => 0,
+ ],
],
]], $container);
@@ -234,13 +255,33 @@ public function testShouldLoadJobServicesIfEnabled()
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => [],
- 'job' => true,
+ 'default' => [
+ 'transport' => [],
+ 'client' => null,
+ 'job' => true,
+ ],
]], $container);
self::assertTrue($container->hasDefinition(JobRunner::class));
}
+ public function testShouldThrowExceptionIfClientIsNotEnabledOnJobLoad()
+ {
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Client is required for job-queue.');
+
+ $container = $this->getContainerBuilder(true);
+
+ $extension = new EnqueueExtension();
+
+ $extension->load([[
+ 'default' => [
+ 'transport' => [],
+ 'job' => true,
+ ],
+ ]], $container);
+ }
+
public function testShouldNotLoadJobServicesIfDisabled()
{
$container = $this->getContainerBuilder(true);
@@ -248,8 +289,10 @@ public function testShouldNotLoadJobServicesIfDisabled()
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => [],
- 'job' => false,
+ 'default' => [
+ 'transport' => [],
+ 'job' => false,
+ ],
]], $container);
self::assertFalse($container->hasDefinition(JobRunner::class));
@@ -271,9 +314,11 @@ public function testShouldLoadDoctrinePingConnectionExtensionServiceIfEnabled()
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => [],
- 'extensions' => [
- 'doctrine_ping_connection_extension' => true,
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'doctrine_ping_connection_extension' => true,
+ ],
],
]], $container);
@@ -287,9 +332,11 @@ public function testShouldNotLoadDoctrinePingConnectionExtensionServiceIfDisable
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => [],
- 'extensions' => [
- 'doctrine_ping_connection_extension' => false,
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'doctrine_ping_connection_extension' => false,
+ ],
],
]], $container);
@@ -303,9 +350,11 @@ public function testShouldLoadDoctrineClearIdentityMapExtensionServiceIfEnabled(
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => [],
- 'extensions' => [
- 'doctrine_clear_identity_map_extension' => true,
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'doctrine_clear_identity_map_extension' => true,
+ ],
],
]], $container);
@@ -319,15 +368,125 @@ public function testShouldNotLoadDoctrineClearIdentityMapExtensionServiceIfDisab
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => [],
- 'extensions' => [
- 'doctrine_clear_identity_map_extension' => false,
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'doctrine_clear_identity_map_extension' => false,
+ ],
],
]], $container);
self::assertFalse($container->hasDefinition('enqueue.consumption.doctrine_clear_identity_map_extension'));
}
+ public function testShouldLoadDoctrineOdmClearIdentityMapExtensionServiceIfEnabled()
+ {
+ $container = $this->getContainerBuilder(true);
+
+ $extension = new EnqueueExtension();
+
+ $extension->load([[
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'doctrine_odm_clear_identity_map_extension' => true,
+ ],
+ ],
+ ]], $container);
+
+ self::assertTrue($container->hasDefinition('enqueue.consumption.doctrine_odm_clear_identity_map_extension'));
+ }
+
+ public function testShouldNotLoadDoctrineOdmClearIdentityMapExtensionServiceIfDisabled()
+ {
+ $container = $this->getContainerBuilder(true);
+
+ $extension = new EnqueueExtension();
+
+ $extension->load([[
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'doctrine_odm_clear_identity_map_extension' => false,
+ ],
+ ],
+ ]], $container);
+
+ self::assertFalse($container->hasDefinition('enqueue.consumption.doctrine_odm_clear_identity_map_extension'));
+ }
+
+ public function testShouldLoadDoctrineClosedEntityManagerExtensionServiceIfEnabled()
+ {
+ $container = $this->getContainerBuilder(true);
+
+ $extension = new EnqueueExtension();
+
+ $extension->load([[
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'doctrine_closed_entity_manager_extension' => true,
+ ],
+ ],
+ ]], $container);
+
+ self::assertTrue($container->hasDefinition('enqueue.consumption.doctrine_closed_entity_manager_extension'));
+ }
+
+ public function testShouldNotLoadDoctrineClosedEntityManagerExtensionServiceIfDisabled()
+ {
+ $container = $this->getContainerBuilder(true);
+
+ $extension = new EnqueueExtension();
+
+ $extension->load([[
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'doctrine_closed_entity_manager_extension' => false,
+ ],
+ ],
+ ]], $container);
+
+ self::assertFalse($container->hasDefinition('enqueue.consumption.doctrine_closed_entity_manager_extension'));
+ }
+
+ public function testShouldLoadResetServicesExtensionServiceIfEnabled()
+ {
+ $container = $this->getContainerBuilder(true);
+
+ $extension = new EnqueueExtension();
+
+ $extension->load([[
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'reset_services_extension' => true,
+ ],
+ ],
+ ]], $container);
+
+ self::assertTrue($container->hasDefinition('enqueue.consumption.reset_services_extension'));
+ }
+
+ public function testShouldNotLoadResetServicesExtensionServiceIfDisabled()
+ {
+ $container = $this->getContainerBuilder(true);
+
+ $extension = new EnqueueExtension();
+
+ $extension->load([[
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'reset_services_extension' => false,
+ ],
+ ],
+ ]], $container);
+
+ self::assertFalse($container->hasDefinition('enqueue.consumption.reset_services_extension'));
+ }
+
public function testShouldLoadSignalExtensionServiceIfEnabled()
{
$container = $this->getContainerBuilder(true);
@@ -335,9 +494,11 @@ public function testShouldLoadSignalExtensionServiceIfEnabled()
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => [],
- 'extensions' => [
- 'signal_extension' => true,
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'signal_extension' => true,
+ ],
],
]], $container);
@@ -351,9 +512,11 @@ public function testShouldNotLoadSignalExtensionServiceIfDisabled()
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => [],
- 'extensions' => [
- 'signal_extension' => false,
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'signal_extension' => false,
+ ],
],
]], $container);
@@ -367,9 +530,11 @@ public function testShouldLoadReplyExtensionServiceIfEnabled()
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => [],
- 'extensions' => [
- 'reply_extension' => true,
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'reply_extension' => true,
+ ],
],
]], $container);
@@ -383,9 +548,11 @@ public function testShouldNotLoadReplyExtensionServiceIfDisabled()
$extension = new EnqueueExtension();
$extension->load([[
- 'transport' => [],
- 'extensions' => [
- 'reply_extension' => false,
+ 'default' => [
+ 'transport' => [],
+ 'extensions' => [
+ 'reply_extension' => false,
+ ],
],
]], $container);
@@ -426,11 +593,13 @@ public function testShouldConfigureQueueConsumer()
$extension = new EnqueueExtension();
$extension->load([[
- 'client' => [],
- 'transport' => [
- ],
- 'consumption' => [
- 'receive_timeout' => 456,
+ 'default' => [
+ 'client' => [],
+ 'transport' => [
+ ],
+ 'consumption' => [
+ 'receive_timeout' => 456,
+ ],
],
]], $container);
@@ -443,14 +612,63 @@ public function testShouldConfigureQueueConsumer()
$this->assertSame(456, $def->getArgument(4));
}
+ public function testShouldSetPropertyWithAllConfiguredTransports()
+ {
+ $container = $this->getContainerBuilder(true);
+
+ $extension = new EnqueueExtension();
+ $extension->load([[
+ 'default' => [
+ 'transport' => 'default:',
+ 'client' => [],
+ ],
+ 'foo' => [
+ 'transport' => 'foo:',
+ 'client' => [],
+ ],
+ 'bar' => [
+ 'transport' => 'bar:',
+ 'client' => [],
+ ],
+ ]], $container);
+
+ $this->assertTrue($container->hasParameter('enqueue.transports'));
+ $this->assertEquals(['default', 'foo', 'bar'], $container->getParameter('enqueue.transports'));
+ }
+
+ public function testShouldSetPropertyWithAllConfiguredClients()
+ {
+ $container = $this->getContainerBuilder(true);
+
+ $extension = new EnqueueExtension();
+ $extension->load([[
+ 'default' => [
+ 'transport' => 'default:',
+ 'client' => [],
+ ],
+ 'foo' => [
+ 'transport' => 'foo:',
+ ],
+ 'bar' => [
+ 'transport' => 'bar:',
+ 'client' => [],
+ ],
+ ]], $container);
+
+ $this->assertTrue($container->hasParameter('enqueue.clients'));
+ $this->assertEquals(['default', 'bar'], $container->getParameter('enqueue.clients'));
+ }
+
public function testShouldLoadProcessAutoconfigureChildDefinition()
{
$container = $this->getContainerBuilder(true);
$extension = new EnqueueExtension();
$extension->load([[
- 'client' => [],
- 'transport' => [],
+ 'default' => [
+ 'client' => [],
+ 'transport' => [],
+ ],
]], $container);
$autoconfigured = $container->getAutoconfiguredInstanceof();
diff --git a/pkg/enqueue-bundle/Tests/Unit/EnqueueBundleTest.php b/pkg/enqueue-bundle/Tests/Unit/EnqueueBundleTest.php
index d93a1f1f9..7d5b0232b 100644
--- a/pkg/enqueue-bundle/Tests/Unit/EnqueueBundleTest.php
+++ b/pkg/enqueue-bundle/Tests/Unit/EnqueueBundleTest.php
@@ -15,9 +15,4 @@ public function testShouldExtendBundleClass()
{
$this->assertClassExtends(Bundle::class, EnqueueBundle::class);
}
-
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new EnqueueBundle();
- }
}
diff --git a/pkg/enqueue-bundle/Tests/Unit/Profiler/MessageQueueCollectorTest.php b/pkg/enqueue-bundle/Tests/Unit/Profiler/MessageQueueCollectorTest.php
index bdc21bf29..d6d638d75 100644
--- a/pkg/enqueue-bundle/Tests/Unit/Profiler/MessageQueueCollectorTest.php
+++ b/pkg/enqueue-bundle/Tests/Unit/Profiler/MessageQueueCollectorTest.php
@@ -2,11 +2,13 @@
namespace Enqueue\Bundle\Tests\Unit\Profiler;
+use DMS\PHPUnitExtensions\ArraySubset\Assert;
use Enqueue\Bundle\Profiler\MessageQueueCollector;
use Enqueue\Client\MessagePriority;
use Enqueue\Client\ProducerInterface;
use Enqueue\Client\TraceableProducer;
use Enqueue\Test\ClassExtensionTrait;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
@@ -21,64 +23,82 @@ public function testShouldExtendDataCollectorClass()
$this->assertClassExtends(DataCollector::class, MessageQueueCollector::class);
}
- public function testCouldBeConstructedWithMessageProducerAsFirstArgument()
- {
- new MessageQueueCollector($this->createProducerMock());
- }
-
public function testShouldReturnExpectedName()
{
- $collector = new MessageQueueCollector($this->createProducerMock());
+ $collector = new MessageQueueCollector();
$this->assertEquals('enqueue.message_queue', $collector->getName());
}
public function testShouldReturnEmptySentMessageArrayIfNotTraceableProducer()
{
- $collector = new MessageQueueCollector($this->createProducerMock());
+ $collector = new MessageQueueCollector();
+ $collector->addProducer('default', $this->createProducerMock());
$collector->collect(new Request(), new Response());
$this->assertSame([], $collector->getSentMessages());
}
- public function testShouldReturnSentMessageArrayTakenFromTraceableProducer()
+ public function testShouldReturnSentMessageArrayTakenFromTraceableProducers()
{
- $producer = new TraceableProducer($this->createProducerMock());
- $producer->sendEvent('fooTopic', 'fooMessage');
- $producer->sendCommand('barCommand', 'barMessage');
+ $producer1 = new TraceableProducer($this->createProducerMock());
+ $producer1->sendEvent('fooTopic1', 'fooMessage');
+ $producer1->sendCommand('barCommand1', 'barMessage');
+
+ $producer2 = new TraceableProducer($this->createProducerMock());
+ $producer2->sendEvent('fooTopic2', 'fooMessage');
- $collector = new MessageQueueCollector($producer);
+ $collector = new MessageQueueCollector();
+ $collector->addProducer('foo', $producer1);
+ $collector->addProducer('bar', $producer2);
$collector->collect(new Request(), new Response());
- $this->assertEquals(
+ Assert::assertArraySubset(
[
- [
- 'topic' => 'fooTopic',
- 'command' => null,
- 'body' => 'fooMessage',
- 'headers' => [],
- 'properties' => [],
- 'priority' => null,
- 'expire' => null,
- 'delay' => null,
- 'timestamp' => null,
- 'contentType' => null,
- 'messageId' => null,
+ 'foo' => [
+ [
+ 'topic' => 'fooTopic1',
+ 'command' => null,
+ 'body' => 'fooMessage',
+ 'headers' => [],
+ 'properties' => [],
+ 'priority' => null,
+ 'expire' => null,
+ 'delay' => null,
+ 'timestamp' => null,
+ 'contentType' => null,
+ 'messageId' => null,
+ ],
+ [
+ 'topic' => null,
+ 'command' => 'barCommand1',
+ 'body' => 'barMessage',
+ 'headers' => [],
+ 'properties' => [],
+ 'priority' => null,
+ 'expire' => null,
+ 'delay' => null,
+ 'timestamp' => null,
+ 'contentType' => null,
+ 'messageId' => null,
+ ],
],
- [
- 'topic' => null,
- 'command' => 'barCommand',
- 'body' => 'barMessage',
- 'headers' => [],
- 'properties' => [],
- 'priority' => null,
- 'expire' => null,
- 'delay' => null,
- 'timestamp' => null,
- 'contentType' => null,
- 'messageId' => null,
+ 'bar' => [
+ [
+ 'topic' => 'fooTopic2',
+ 'command' => null,
+ 'body' => 'fooMessage',
+ 'headers' => [],
+ 'properties' => [],
+ 'priority' => null,
+ 'expire' => null,
+ 'delay' => null,
+ 'timestamp' => null,
+ 'contentType' => null,
+ 'messageId' => null,
+ ],
],
],
$collector->getSentMessages()
@@ -87,21 +107,21 @@ public function testShouldReturnSentMessageArrayTakenFromTraceableProducer()
public function testShouldPrettyPrintKnownPriority()
{
- $collector = new MessageQueueCollector($this->createProducerMock());
+ $collector = new MessageQueueCollector();
$this->assertEquals('normal', $collector->prettyPrintPriority(MessagePriority::NORMAL));
}
public function testShouldPrettyPrintUnknownPriority()
{
- $collector = new MessageQueueCollector($this->createProducerMock());
+ $collector = new MessageQueueCollector();
$this->assertEquals('unknownPriority', $collector->prettyPrintPriority('unknownPriority'));
}
public function testShouldEnsureStringKeepStringSame()
{
- $collector = new MessageQueueCollector($this->createProducerMock());
+ $collector = new MessageQueueCollector();
$this->assertEquals('foo', $collector->ensureString('foo'));
$this->assertEquals('bar baz', $collector->ensureString('bar baz'));
@@ -109,13 +129,13 @@ public function testShouldEnsureStringKeepStringSame()
public function testShouldEnsureStringEncodeArrayToJson()
{
- $collector = new MessageQueueCollector($this->createProducerMock());
+ $collector = new MessageQueueCollector();
$this->assertEquals('["foo","bar"]', $collector->ensureString(['foo', 'bar']));
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ProducerInterface
+ * @return MockObject|ProducerInterface
*/
protected function createProducerMock()
{
@@ -123,7 +143,7 @@ protected function createProducerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|TraceableProducer
+ * @return MockObject|TraceableProducer
*/
protected function createTraceableProducerMock()
{
diff --git a/pkg/enqueue-bundle/Tests/fix_composer_json.php b/pkg/enqueue-bundle/Tests/fix_composer_json.php
index fc430e276..5c80237ea 100644
--- a/pkg/enqueue-bundle/Tests/fix_composer_json.php
+++ b/pkg/enqueue-bundle/Tests/fix_composer_json.php
@@ -4,6 +4,7 @@
$composerJson = json_decode(file_get_contents(__DIR__.'/../composer.json'), true);
-$composerJson['config']['platform']['ext-amqp'] = '1.7';
+$composerJson['config']['platform']['ext-amqp'] = '1.9.3';
+$composerJson['config']['platform']['ext-mongo'] = '1.6.14';
-file_put_contents(__DIR__.'/../composer.json', json_encode($composerJson, JSON_PRETTY_PRINT));
+file_put_contents(__DIR__.'/../composer.json', json_encode($composerJson, \JSON_PRETTY_PRINT));
diff --git a/pkg/enqueue-bundle/composer.json b/pkg/enqueue-bundle/composer.json
index efe06b027..074996a98 100644
--- a/pkg/enqueue-bundle/composer.json
+++ b/pkg/enqueue-bundle/composer.json
@@ -6,12 +6,12 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "symfony/framework-bundle": "^3.4|^4",
- "queue-interop/amqp-interop": "0.8.x-dev",
- "queue-interop/queue-interop": "0.7.x-dev",
- "enqueue/enqueue": "0.9.x-dev",
- "enqueue/null": "0.9.x-dev"
+ "php": "^8.1",
+ "symfony/framework-bundle": "^7.0|^8.0",
+ "queue-interop/amqp-interop": "^0.8.2",
+ "queue-interop/queue-interop": "^0.8",
+ "enqueue/enqueue": "^0.10",
+ "enqueue/null": "^0.10"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -21,24 +21,28 @@
"docs": "https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md"
},
"require-dev": {
- "phpunit/phpunit": "~5.5",
- "enqueue/stomp": "0.9.x-dev",
- "enqueue/amqp-ext": "0.9.x-dev",
- "enqueue/amqp-lib": "0.9.x-dev",
- "enqueue/amqp-bunny": "0.9.x-dev",
- "enqueue/job-queue": "0.9.x-dev",
- "enqueue/fs": "0.9.x-dev",
- "enqueue/redis": "0.9.x-dev",
- "enqueue/dbal": "0.9.x-dev",
- "enqueue/sqs": "0.9.x-dev",
- "enqueue/gps": "0.9.x-dev",
- "enqueue/test": "0.9.x-dev",
- "enqueue/async-event-dispatcher": "0.9.x-dev",
- "enqueue/async-command": "0.9.x-dev",
- "php-amqplib/php-amqplib": "^2.7",
- "doctrine/doctrine-bundle": "~1.2",
- "symfony/browser-kit": "^3.4|^4",
- "symfony/expression-language": "^3.4|^4"
+ "phpunit/phpunit": "^9.5",
+ "enqueue/stomp": "0.10.x-dev",
+ "enqueue/amqp-ext": "0.10.x-dev",
+ "enqueue/amqp-lib": "0.10.x-dev",
+ "enqueue/amqp-bunny": "0.10.x-dev",
+ "enqueue/job-queue": "0.10.x-dev",
+ "enqueue/fs": "0.10.x-dev",
+ "enqueue/redis": "0.10.x-dev",
+ "enqueue/dbal": "0.10.x-dev",
+ "enqueue/sqs": "0.10.x-dev",
+ "enqueue/gps": "0.10.x-dev",
+ "enqueue/test": "0.10.x-dev",
+ "enqueue/async-event-dispatcher": "0.10.x-dev",
+ "enqueue/async-command": "0.10.x-dev",
+ "php-amqplib/php-amqplib": "^3.0",
+ "doctrine/doctrine-bundle": "^2.5|^3.1",
+ "doctrine/mongodb-odm-bundle": "^3.5|^4.3|^5.0",
+ "alcaeus/mongo-php-adapter": "^1.0",
+ "symfony/browser-kit": "^7.0|^8.0",
+ "symfony/expression-language": "^7.0|^8.0",
+ "symfony/validator": "^7.0|^8.0",
+ "symfony/yaml": "^7.0|^8.0"
},
"suggest": {
"enqueue/async-command": "If want to run Symfony command via message queue",
@@ -52,7 +56,12 @@
},
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
+ },
+ "config": {
+ "allow-plugins": {
+ "php-http/discovery": true
+ }
}
}
diff --git a/pkg/enqueue-bundle/phpunit.xml.dist b/pkg/enqueue-bundle/phpunit.xml.dist
index ac0770ea9..974d2c3f5 100644
--- a/pkg/enqueue-bundle/phpunit.xml.dist
+++ b/pkg/enqueue-bundle/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/enqueue/.gitattributes b/pkg/enqueue/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/enqueue/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/enqueue/.github/workflows/ci.yml b/pkg/enqueue/.github/workflows/ci.yml
new file mode 100644
index 000000000..faaaaf9f3
--- /dev/null
+++ b/pkg/enqueue/.github/workflows/ci.yml
@@ -0,0 +1,30 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+ extensions: mongodb
+
+ - run: php Tests/fix_composer_json.php
+
+ - uses: "ramsey/composer-install@v3"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/enqueue/.travis.yml b/pkg/enqueue/.travis.yml
deleted file mode 100644
index 2c830d0a6..000000000
--- a/pkg/enqueue/.travis.yml
+++ /dev/null
@@ -1,27 +0,0 @@
-sudo: false
-
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
-
-services:
- - mongodb
-
-before_install:
- - echo "extension = mongodb.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - php Tests/fix_composer_json.php
- - composer self-update
- - composer install
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/enqueue/Client/ChainExtension.php b/pkg/enqueue/Client/ChainExtension.php
index ba0fc888d..655b75f6a 100644
--- a/pkg/enqueue/Client/ChainExtension.php
+++ b/pkg/enqueue/Client/ChainExtension.php
@@ -5,46 +5,98 @@
final class ChainExtension implements ExtensionInterface
{
/**
- * @var ExtensionInterface[]
+ * @var PreSendEventExtensionInterface[]
*/
- private $extensions;
+ private $preSendEventExtensions;
/**
- * @param ExtensionInterface[] $extensions
+ * @var PreSendCommandExtensionInterface[]
*/
+ private $preSendCommandExtensions;
+
+ /**
+ * @var DriverPreSendExtensionInterface[]
+ */
+ private $driverPreSendExtensions;
+
+ /**
+ * @var PostSendExtensionInterface[]
+ */
+ private $postSendExtensions;
+
public function __construct(array $extensions)
{
- $this->extensions = [];
- array_walk($extensions, function (ExtensionInterface $extension) {
- $this->extensions[] = $extension;
+ $this->preSendEventExtensions = [];
+ $this->preSendCommandExtensions = [];
+ $this->driverPreSendExtensions = [];
+ $this->postSendExtensions = [];
+
+ array_walk($extensions, function ($extension) {
+ if ($extension instanceof ExtensionInterface) {
+ $this->preSendEventExtensions[] = $extension;
+ $this->preSendCommandExtensions[] = $extension;
+ $this->driverPreSendExtensions[] = $extension;
+ $this->postSendExtensions[] = $extension;
+
+ return;
+ }
+
+ $extensionValid = false;
+ if ($extension instanceof PreSendEventExtensionInterface) {
+ $this->preSendEventExtensions[] = $extension;
+
+ $extensionValid = true;
+ }
+
+ if ($extension instanceof PreSendCommandExtensionInterface) {
+ $this->preSendCommandExtensions[] = $extension;
+
+ $extensionValid = true;
+ }
+
+ if ($extension instanceof DriverPreSendExtensionInterface) {
+ $this->driverPreSendExtensions[] = $extension;
+
+ $extensionValid = true;
+ }
+
+ if ($extension instanceof PostSendExtensionInterface) {
+ $this->postSendExtensions[] = $extension;
+
+ $extensionValid = true;
+ }
+
+ if (false == $extensionValid) {
+ throw new \LogicException(sprintf('Invalid extension given %s', $extension::class));
+ }
});
}
- public function onPreSendEvent(PreSend $event): void
+ public function onPreSendEvent(PreSend $context): void
{
- foreach ($this->extensions as $extension) {
- $extension->onPreSendEvent($event);
+ foreach ($this->preSendEventExtensions as $extension) {
+ $extension->onPreSendEvent($context);
}
}
- public function onPreSendCommand(PreSend $event): void
+ public function onPreSendCommand(PreSend $context): void
{
- foreach ($this->extensions as $extension) {
- $extension->onPreSendCommand($event);
+ foreach ($this->preSendCommandExtensions as $extension) {
+ $extension->onPreSendCommand($context);
}
}
public function onDriverPreSend(DriverPreSend $context): void
{
- foreach ($this->extensions as $extension) {
+ foreach ($this->driverPreSendExtensions as $extension) {
$extension->onDriverPreSend($context);
}
}
- public function onPostSend(PostSend $event): void
+ public function onPostSend(PostSend $context): void
{
- foreach ($this->extensions as $extension) {
- $extension->onPostSend($event);
+ foreach ($this->postSendExtensions as $extension) {
+ $extension->onPostSend($context);
}
}
}
diff --git a/pkg/enqueue/Client/CommandSubscriberInterface.php b/pkg/enqueue/Client/CommandSubscriberInterface.php
index 5bbe78efe..d7b06daaf 100644
--- a/pkg/enqueue/Client/CommandSubscriberInterface.php
+++ b/pkg/enqueue/Client/CommandSubscriberInterface.php
@@ -2,6 +2,15 @@
namespace Enqueue\Client;
+/**
+ * @phpstan-type CommandConfig = array{
+ * command: string,
+ * processor?: string,
+ * queue?: string,
+ * prefix_queue?: bool,
+ * exclusive?: bool,
+ * }
+ */
interface CommandSubscriberInterface
{
/**
@@ -41,9 +50,11 @@ interface CommandSubscriberInterface
* queue, processor, prefix_queue, and exclusive are optional.
* It is possible to pass other options, they could be accessible on a route instance through options.
*
- * Note: If you set queueNameHardcoded to true then the queueName is used as is and therefor the driver is not used to create a transport queue name.
+ * Note: If you set "prefix_queue" to true then the "queue" is used as is and therefor the driver is not used to create a transport queue name.
*
* @return string|array
+ *
+ * @phpstan-return string|CommandConfig|array
*/
public static function getSubscribedCommand();
}
diff --git a/pkg/enqueue/Client/Config.php b/pkg/enqueue/Client/Config.php
index ef68fb632..8210dff68 100644
--- a/pkg/enqueue/Client/Config.php
+++ b/pkg/enqueue/Client/Config.php
@@ -4,13 +4,13 @@
class Config
{
- const TOPIC = 'enqueue.topic';
- const COMMAND = 'enqueue.command';
- const PROCESSOR = 'enqueue.processor';
- const EXPIRE = 'enqueue.expire';
- const PRIORITY = 'enqueue.priority';
- const DELAY = 'enqueue.delay';
- const CONTENT_TYPE = 'enqueue.content_type';
+ public const TOPIC = 'enqueue.topic';
+ public const COMMAND = 'enqueue.command';
+ public const PROCESSOR = 'enqueue.processor';
+ public const EXPIRE = 'enqueue.expire';
+ public const PRIORITY = 'enqueue.priority';
+ public const DELAY = 'enqueue.delay';
+ public const CONTENT_TYPE = 'enqueue.content_type';
/**
* @var string
@@ -52,8 +52,22 @@ class Config
*/
private $transportConfig;
- public function __construct(string $prefix, string $app, string $routerTopic, string $routerQueue, string $defaultQueue, string $routerProcessor, array $transportConfig = [])
- {
+ /**
+ * @var array
+ */
+ private $driverConfig;
+
+ public function __construct(
+ string $prefix,
+ string $separator,
+ string $app,
+ string $routerTopic,
+ string $routerQueue,
+ string $defaultQueue,
+ string $routerProcessor,
+ array $transportConfig,
+ array $driverConfig,
+ ) {
$this->prefix = trim($prefix);
$this->app = trim($app);
@@ -78,8 +92,9 @@ public function __construct(string $prefix, string $app, string $routerTopic, st
}
$this->transportConfig = $transportConfig;
+ $this->driverConfig = $driverConfig;
- $this->separator = '.';
+ $this->separator = $separator;
}
public function getPrefix(): string
@@ -117,33 +132,47 @@ public function getRouterProcessor(): string
return $this->routerProcessor;
}
- /**
- * @deprecated
- *
- * @param null|mixed $default
- */
public function getTransportOption(string $name, $default = null)
{
return array_key_exists($name, $this->transportConfig) ? $this->transportConfig[$name] : $default;
}
+ public function getTransportOptions(): array
+ {
+ return $this->transportConfig;
+ }
+
+ public function getDriverOption(string $name, $default = null)
+ {
+ return array_key_exists($name, $this->driverConfig) ? $this->driverConfig[$name] : $default;
+ }
+
+ public function getDriverOptions(): array
+ {
+ return $this->driverConfig;
+ }
+
public static function create(
- string $prefix = null,
- string $app = null,
- string $routerTopic = null,
- string $routerQueue = null,
- string $defaultQueue = null,
- string $routerProcessor = null,
- array $transportConfig = []
+ ?string $prefix = null,
+ ?string $separator = null,
+ ?string $app = null,
+ ?string $routerTopic = null,
+ ?string $routerQueue = null,
+ ?string $defaultQueue = null,
+ ?string $routerProcessor = null,
+ array $transportConfig = [],
+ array $driverConfig = [],
): self {
- return new static(
+ return new self(
$prefix ?: '',
+ $separator ?: '.',
$app ?: '',
$routerTopic ?: 'router',
$routerQueue ?: 'default',
$defaultQueue ?: 'default',
$routerProcessor ?: 'router',
- $transportConfig
+ $transportConfig,
+ $driverConfig
);
}
}
diff --git a/pkg/enqueue/Client/ConsumptionExtension/DelayRedeliveredMessageExtension.php b/pkg/enqueue/Client/ConsumptionExtension/DelayRedeliveredMessageExtension.php
index 77e3bc451..475e2cf5b 100644
--- a/pkg/enqueue/Client/ConsumptionExtension/DelayRedeliveredMessageExtension.php
+++ b/pkg/enqueue/Client/ConsumptionExtension/DelayRedeliveredMessageExtension.php
@@ -9,7 +9,7 @@
class DelayRedeliveredMessageExtension implements MessageReceivedExtensionInterface
{
- const PROPERTY_REDELIVER_COUNT = 'enqueue.redelivery_count';
+ public const PROPERTY_REDELIVER_COUNT = 'enqueue.redelivery_count';
/**
* @var DriverInterface
@@ -24,8 +24,7 @@ class DelayRedeliveredMessageExtension implements MessageReceivedExtensionInterf
private $delay;
/**
- * @param DriverInterface $driver
- * @param int $delay The number of seconds the message should be delayed
+ * @param int $delay The number of seconds the message should be delayed
*/
public function __construct(DriverInterface $driver, $delay)
{
diff --git a/pkg/enqueue/Client/ConsumptionExtension/ExclusiveCommandExtension.php b/pkg/enqueue/Client/ConsumptionExtension/ExclusiveCommandExtension.php
index a76e49f30..7ab88ae0f 100644
--- a/pkg/enqueue/Client/ConsumptionExtension/ExclusiveCommandExtension.php
+++ b/pkg/enqueue/Client/ConsumptionExtension/ExclusiveCommandExtension.php
@@ -64,7 +64,7 @@ private function buildMap(): array
continue;
}
- $queueName = $this->driver->createQueue($route->getQueue())->getQueueName();
+ $queueName = $this->driver->createRouteQueue($route)->getQueueName();
if (array_key_exists($queueName, $map)) {
throw new \LogicException('The queue name has been already bound by another exclusive command processor');
}
diff --git a/pkg/enqueue/Client/ConsumptionExtension/SetRouterPropertiesExtension.php b/pkg/enqueue/Client/ConsumptionExtension/SetRouterPropertiesExtension.php
index 16558867e..0d2278349 100644
--- a/pkg/enqueue/Client/ConsumptionExtension/SetRouterPropertiesExtension.php
+++ b/pkg/enqueue/Client/ConsumptionExtension/SetRouterPropertiesExtension.php
@@ -14,9 +14,6 @@ class SetRouterPropertiesExtension implements MessageReceivedExtensionInterface
*/
private $driver;
- /**
- * @param DriverInterface $driver
- */
public function __construct(DriverInterface $driver)
{
$this->driver = $driver;
@@ -25,6 +22,9 @@ public function __construct(DriverInterface $driver)
public function onMessageReceived(MessageReceived $context): void
{
$message = $context->getMessage();
+ if (false == $message->getProperty(Config::TOPIC)) {
+ return;
+ }
if ($message->getProperty(Config::PROCESSOR)) {
return;
}
diff --git a/pkg/enqueue/Client/ConsumptionExtension/SetupBrokerExtension.php b/pkg/enqueue/Client/ConsumptionExtension/SetupBrokerExtension.php
index e35580794..44d610fb9 100644
--- a/pkg/enqueue/Client/ConsumptionExtension/SetupBrokerExtension.php
+++ b/pkg/enqueue/Client/ConsumptionExtension/SetupBrokerExtension.php
@@ -18,9 +18,6 @@ class SetupBrokerExtension implements StartExtensionInterface
*/
private $isDone;
- /**
- * @param DriverInterface $driver
- */
public function __construct(DriverInterface $driver)
{
$this->driver = $driver;
diff --git a/pkg/enqueue/Client/DelegateProcessor.php b/pkg/enqueue/Client/DelegateProcessor.php
index 18985b454..7582c52dc 100644
--- a/pkg/enqueue/Client/DelegateProcessor.php
+++ b/pkg/enqueue/Client/DelegateProcessor.php
@@ -14,25 +14,19 @@ class DelegateProcessor implements Processor
*/
private $registry;
- /**
- * @param ProcessorRegistryInterface $registry
- */
public function __construct(ProcessorRegistryInterface $registry)
{
$this->registry = $registry;
}
/**
- * {@inheritdoc}
+ * @return string|object
*/
public function process(InteropMessage $message, Context $context)
{
$processorName = $message->getProperty(Config::PROCESSOR);
if (false == $processorName) {
- throw new \LogicException(sprintf(
- 'Got message without required parameter: "%s"',
- Config::PROCESSOR
- ));
+ throw new \LogicException(sprintf('Got message without required parameter: "%s"', Config::PROCESSOR));
}
return $this->registry->get($processorName)->process($message, $context);
diff --git a/pkg/enqueue/Client/Driver/AmqpDriver.php b/pkg/enqueue/Client/Driver/AmqpDriver.php
index be62753bf..1def3fb23 100644
--- a/pkg/enqueue/Client/Driver/AmqpDriver.php
+++ b/pkg/enqueue/Client/Driver/AmqpDriver.php
@@ -2,7 +2,7 @@
declare(strict_types=1);
-namespace Enqueue\Client\Driver;
+namespace Enqueue\Client\Driver;
use Enqueue\AmqpExt\AmqpProducer;
use Enqueue\Client\Message;
@@ -45,11 +45,7 @@ public function createTransportMessage(Message $clientMessage): InteropMessage
$priorityMap = $this->getPriorityMap();
if ($priority = $clientMessage->getPriority()) {
if (false == array_key_exists($priority, $priorityMap)) {
- throw new \InvalidArgumentException(sprintf(
- 'Cant convert client priority "%s" to transport one. Could be one of "%s"',
- $priority,
- implode('", "', array_keys($priorityMap))
- ));
+ throw new \InvalidArgumentException(sprintf('Cant convert client priority "%s" to transport one. Could be one of "%s"', $priority, implode('", "', array_keys($priorityMap))));
}
$transportMessage->setPriority($priorityMap[$priority]);
@@ -58,7 +54,7 @@ public function createTransportMessage(Message $clientMessage): InteropMessage
return $transportMessage;
}
- public function setupBroker(LoggerInterface $logger = null): void
+ public function setupBroker(?LoggerInterface $logger = null): void
{
$logger = $logger ?: new NullLogger();
$log = function ($text, ...$args) use ($logger) {
diff --git a/pkg/enqueue/Client/Driver/DbalDriver.php b/pkg/enqueue/Client/Driver/DbalDriver.php
index 8b1f32655..34875eff7 100644
--- a/pkg/enqueue/Client/Driver/DbalDriver.php
+++ b/pkg/enqueue/Client/Driver/DbalDriver.php
@@ -16,7 +16,7 @@ public function __construct(DbalContext $context, ...$args)
parent::__construct($context, ...$args);
}
- public function setupBroker(LoggerInterface $logger = null): void
+ public function setupBroker(?LoggerInterface $logger = null): void
{
$logger = $logger ?: new NullLogger();
$log = function ($text, ...$args) use ($logger) {
diff --git a/pkg/enqueue/Client/Driver/FsDriver.php b/pkg/enqueue/Client/Driver/FsDriver.php
index 9de59c23b..f578b172d 100644
--- a/pkg/enqueue/Client/Driver/FsDriver.php
+++ b/pkg/enqueue/Client/Driver/FsDriver.php
@@ -1,6 +1,6 @@
context = $context;
$this->config = $config;
$this->routeCollection = $routeCollection;
}
- public function sendToRouter(Message $message): void
+ public function sendToRouter(Message $message): DriverSendResult
{
if ($message->getProperty(Config::COMMAND)) {
throw new \LogicException('Command must not be send to router but go directly to its processor.');
@@ -59,16 +60,20 @@ public function sendToRouter(Message $message): void
$producer = $this->getContext()->createProducer();
$this->doSendToRouter($producer, $topic, $transportMessage);
+
+ return new DriverSendResult($topic, $transportMessage);
}
- public function sendToProcessor(Message $message): void
+ public function sendToProcessor(Message $message): DriverSendResult
{
$topic = $message->getProperty(Config::TOPIC);
$command = $message->getProperty(Config::COMMAND);
/** @var InteropQueue $queue */
$queue = null;
- if ($topic && $processor = $message->getProperty(Config::PROCESSOR)) {
+ $routerProcessor = $this->config->getRouterProcessor();
+ $processor = $message->getProperty(Config::PROCESSOR);
+ if ($topic && $processor && $processor !== $routerProcessor) {
$route = $this->routeCollection->topicAndProcessor($topic, $processor);
if (false == $route) {
throw new \LogicException(sprintf('There is no route for topic "%s" and processor "%s"', $topic, $processor));
@@ -76,8 +81,8 @@ public function sendToProcessor(Message $message): void
$message->setProperty(Config::PROCESSOR, $route->getProcessor());
$queue = $this->createRouteQueue($route);
- } elseif ($topic && false == $message->getProperty(Config::PROCESSOR)) {
- $message->setProperty(Config::PROCESSOR, $this->config->getRouterProcessor());
+ } elseif ($topic && (false == $processor || $processor === $routerProcessor)) {
+ $message->setProperty(Config::PROCESSOR, $routerProcessor);
$queue = $this->createQueue($this->config->getRouterQueue());
} elseif ($command) {
@@ -111,9 +116,11 @@ public function sendToProcessor(Message $message): void
}
$this->doSendToProcessor($producer, $queue, $transportMessage);
+
+ return new DriverSendResult($queue, $transportMessage);
}
- public function setupBroker(LoggerInterface $logger = null): void
+ public function setupBroker(?LoggerInterface $logger = null): void
{
}
diff --git a/pkg/enqueue/Client/Driver/GpsDriver.php b/pkg/enqueue/Client/Driver/GpsDriver.php
index 37a7110c1..32d14f721 100644
--- a/pkg/enqueue/Client/Driver/GpsDriver.php
+++ b/pkg/enqueue/Client/Driver/GpsDriver.php
@@ -20,7 +20,7 @@ public function __construct(GpsContext $context, ...$args)
parent::__construct($context, ...$args);
}
- public function setupBroker(LoggerInterface $logger = null): void
+ public function setupBroker(?LoggerInterface $logger = null): void
{
$logger = $logger ?: new NullLogger();
$log = function ($text, ...$args) use ($logger) {
diff --git a/pkg/enqueue/Client/Driver/MongodbDriver.php b/pkg/enqueue/Client/Driver/MongodbDriver.php
index 19f2c57d3..1c9cff4bc 100644
--- a/pkg/enqueue/Client/Driver/MongodbDriver.php
+++ b/pkg/enqueue/Client/Driver/MongodbDriver.php
@@ -16,7 +16,7 @@ public function __construct(MongodbContext $context, ...$args)
parent::__construct($context, ...$args);
}
- public function setupBroker(LoggerInterface $logger = null): void
+ public function setupBroker(?LoggerInterface $logger = null): void
{
$logger = $logger ?: new NullLogger();
$log = function ($text, ...$args) use ($logger) {
diff --git a/pkg/enqueue/Client/Driver/RabbitMqDriver.php b/pkg/enqueue/Client/Driver/RabbitMqDriver.php
index 096de6d26..f215d555e 100644
--- a/pkg/enqueue/Client/Driver/RabbitMqDriver.php
+++ b/pkg/enqueue/Client/Driver/RabbitMqDriver.php
@@ -1,6 +1,6 @@
debug('[RdKafkaDriver] setup broker');
diff --git a/pkg/enqueue/Client/Driver/SnsQsDriver.php b/pkg/enqueue/Client/Driver/SnsQsDriver.php
new file mode 100644
index 000000000..f4bde10c2
--- /dev/null
+++ b/pkg/enqueue/Client/Driver/SnsQsDriver.php
@@ -0,0 +1,90 @@
+debug(sprintf('[SqsQsDriver] '.$text, ...$args));
+ };
+
+ // setup router
+ $routerTopic = $this->createRouterTopic();
+ $log('Declare router topic: %s', $routerTopic->getTopicName());
+ $this->getContext()->declareTopic($routerTopic);
+
+ $routerQueue = $this->createQueue($this->getConfig()->getRouterQueue());
+ $log('Declare router queue: %s', $routerQueue->getQueueName());
+ $this->getContext()->declareQueue($routerQueue);
+
+ $log('Bind router queue to topic: %s -> %s', $routerQueue->getQueueName(), $routerTopic->getTopicName());
+ $this->getContext()->bind($routerTopic, $routerQueue);
+
+ // setup queues
+ $declaredQueues = [];
+ $declaredTopics = [];
+ foreach ($this->getRouteCollection()->all() as $route) {
+ $queue = $this->createRouteQueue($route);
+ if (false === array_key_exists($queue->getQueueName(), $declaredQueues)) {
+ $log('Declare processor queue: %s', $queue->getQueueName());
+ $this->getContext()->declareQueue($queue);
+
+ $declaredQueues[$queue->getQueueName()] = true;
+ }
+
+ if ($route->isCommand()) {
+ continue;
+ }
+
+ $topic = $this->doCreateTopic($this->createTransportQueueName($route->getSource(), true));
+ if (false === array_key_exists($topic->getTopicName(), $declaredTopics)) {
+ $log('Declare processor topic: %s', $topic->getTopicName());
+ $this->getContext()->declareTopic($topic);
+
+ $declaredTopics[$topic->getTopicName()] = true;
+ }
+
+ $log('Bind processor queue to topic: %s -> %s', $queue->getQueueName(), $topic->getTopicName());
+ $this->getContext()->bind($topic, $queue);
+ }
+ }
+
+ protected function createRouterTopic(): Destination
+ {
+ return $this->doCreateTopic(
+ $this->createTransportRouterTopicName($this->getConfig()->getRouterTopic(), true)
+ );
+ }
+
+ protected function createTransportRouterTopicName(string $name, bool $prefix): string
+ {
+ $name = parent::createTransportRouterTopicName($name, $prefix);
+
+ return str_replace('.', '_dot_', $name);
+ }
+
+ protected function createTransportQueueName(string $name, bool $prefix): string
+ {
+ $name = parent::createTransportQueueName($name, $prefix);
+
+ return str_replace('.', '_dot_', $name);
+ }
+}
diff --git a/pkg/enqueue/Client/Driver/SqsDriver.php b/pkg/enqueue/Client/Driver/SqsDriver.php
index bf66c050c..49b696aae 100644
--- a/pkg/enqueue/Client/Driver/SqsDriver.php
+++ b/pkg/enqueue/Client/Driver/SqsDriver.php
@@ -18,7 +18,7 @@ public function __construct(SqsContext $context, ...$args)
parent::__construct($context, ...$args);
}
- public function setupBroker(LoggerInterface $logger = null): void
+ public function setupBroker(?LoggerInterface $logger = null): void
{
$logger = $logger ?: new NullLogger();
$log = function ($text, ...$args) use ($logger) {
diff --git a/pkg/enqueue/Client/Driver/StompDriver.php b/pkg/enqueue/Client/Driver/StompDriver.php
index 7040c71dd..811ad76e7 100644
--- a/pkg/enqueue/Client/Driver/StompDriver.php
+++ b/pkg/enqueue/Client/Driver/StompDriver.php
@@ -22,7 +22,7 @@ public function __construct(StompContext $context, ...$args)
parent::__construct($context, ...$args);
}
- public function setupBroker(LoggerInterface $logger = null): void
+ public function setupBroker(?LoggerInterface $logger = null): void
{
$logger = $logger ?: new NullLogger();
$logger->debug('[StompDriver] Stomp protocol does not support broker configuration');
diff --git a/pkg/enqueue/Client/Driver/StompManagementClient.php b/pkg/enqueue/Client/Driver/StompManagementClient.php
index c068a57df..0d64450dd 100644
--- a/pkg/enqueue/Client/Driver/StompManagementClient.php
+++ b/pkg/enqueue/Client/Driver/StompManagementClient.php
@@ -24,7 +24,7 @@ public function __construct(Client $client, string $vhost = '/')
public static function create(string $vhost = '/', string $host = 'localhost', int $port = 15672, string $login = 'guest', string $password = 'guest'): self
{
- return new static(new Client(null, 'http://'.$host.':'.$port, $login, $password), $vhost);
+ return new self(new Client(null, 'http://'.$host.':'.$port, $login, $password), $vhost);
}
public function declareQueue(string $name, array $options)
@@ -37,7 +37,7 @@ public function declareExchange(string $name, array $options)
return $this->client->exchanges()->create($this->vhost, $name, $options);
}
- public function bind(string $exchange, string $queue, string $routingKey = null, $arguments = null)
+ public function bind(string $exchange, string $queue, ?string $routingKey = null, $arguments = null)
{
return $this->client->bindings()->create($this->vhost, $exchange, $queue, $routingKey, $arguments);
}
diff --git a/pkg/enqueue/Client/DriverFactory.php b/pkg/enqueue/Client/DriverFactory.php
index 071ec0c62..5c827e7e7 100644
--- a/pkg/enqueue/Client/DriverFactory.php
+++ b/pkg/enqueue/Client/DriverFactory.php
@@ -2,88 +2,39 @@
namespace Enqueue\Client;
-use Enqueue\Client\Driver\RabbitMqDriver;
use Enqueue\Client\Driver\RabbitMqStompDriver;
use Enqueue\Client\Driver\StompManagementClient;
use Enqueue\Dsn\Dsn;
-use Enqueue\Stomp\StompConnectionFactory;
-use Interop\Amqp\AmqpConnectionFactory;
use Interop\Queue\ConnectionFactory;
final class DriverFactory implements DriverFactoryInterface
{
- /**
- * @var Config
- */
- private $config;
-
- /**
- * @var RouteCollection
- */
- private $routeCollection;
-
- public function __construct(Config $config, RouteCollection $routeCollection)
+ public function create(ConnectionFactory $factory, Config $config, RouteCollection $collection): DriverInterface
{
- $this->config = $config;
- $this->routeCollection = $routeCollection;
- }
+ $dsn = $config->getTransportOption('dsn');
- public function create(ConnectionFactory $factory, string $dsn, array $config): DriverInterface
- {
- $dsn = new Dsn($dsn);
+ if (empty($dsn)) {
+ throw new \LogicException('This driver factory relies on dsn option from transport config. The option is empty or not set.');
+ }
- if ($driverInfo = $this->findDriverInfo($dsn, Resources::getAvailableDrivers())) {
- $driverClass = $driverInfo['factoryClass'];
-
- if (RabbitMqDriver::class === $driverClass) {
- if (false == $factory instanceof AmqpConnectionFactory) {
- throw new \LogicException(sprintf(
- 'The factory must be instance of "%s", got "%s"',
- AmqpConnectionFactory::class,
- get_class($factory)
- ));
- }
+ $dsn = Dsn::parseFirst($dsn);
- return new RabbitMqDriver($factory->createContext(), $this->config, $this->routeCollection);
- }
+ if ($driverInfo = $this->findDriverInfo($dsn, Resources::getAvailableDrivers())) {
+ $driverClass = $driverInfo['driverClass'];
if (RabbitMqStompDriver::class === $driverClass) {
- if (false == $factory instanceof StompConnectionFactory) {
- throw new \LogicException(sprintf(
- 'The factory must be instance of "%s", got "%s"',
- StompConnectionFactory::class,
- get_class($factory)
- ));
- }
-
- $managementClient = StompManagementClient::create(
- ltrim($dsn->getPath(), '/'),
- $dsn->getHost() ?: 'localhost',
- $config['management_plugin_port'] ?? 15672,
- (string) $dsn->getUser(),
- (string) $dsn->getPassword()
- );
-
- return new RabbitMqStompDriver($factory->createContext(), $this->config, $this->routeCollection, $managementClient);
+ return $this->createRabbitMqStompDriver($factory, $dsn, $config, $collection);
}
- return new $driverClass($factory->createContext(), $this->config, $this->routeCollection);
+ return new $driverClass($factory->createContext(), $config, $collection);
}
$knownDrivers = Resources::getKnownDrivers();
if ($driverInfo = $this->findDriverInfo($dsn, $knownDrivers)) {
- throw new \LogicException(sprintf(
- 'To use given scheme "%s" a package has to be installed. Run "composer req %s" to add it.',
- $dsn->getScheme(),
- implode(' ', $driverInfo['packages'])
- ));
+ throw new \LogicException(sprintf('To use given scheme "%s" a package has to be installed. Run "composer req %s" to add it.', $dsn->getScheme(), implode(' ', $driverInfo['packages'])));
}
- throw new \LogicException(sprintf(
- 'A given scheme "%s" is not supported. Maybe it is a custom driver, make sure you registered it with "%s::addDriver".',
- $dsn->getScheme(),
- Resources::class
- ));
+ throw new \LogicException(sprintf('A given scheme "%s" is not supported. Maybe it is a custom driver, make sure you registered it with "%s::addDriver".', $dsn->getScheme(), Resources::class));
}
private function findDriverInfo(Dsn $dsn, array $factories): ?array
@@ -121,4 +72,20 @@ private function findDriverInfo(Dsn $dsn, array $factories): ?array
return null;
}
+
+ private function createRabbitMqStompDriver(ConnectionFactory $factory, Dsn $dsn, Config $config, RouteCollection $collection): RabbitMqStompDriver
+ {
+ $defaultManagementHost = $dsn->getHost() ?: $config->getTransportOption('host', 'localhost');
+ $managementVast = ltrim($dsn->getPath() ?? '', '/') ?: $config->getTransportOption('vhost', '/');
+
+ $managementClient = StompManagementClient::create(
+ urldecode($managementVast),
+ $config->getDriverOption('rabbitmq_management_host', $defaultManagementHost),
+ $config->getDriverOption('rabbitmq_management_port', 15672),
+ (string) $dsn->getUser() ?: $config->getTransportOption('user', 'guest'),
+ (string) $dsn->getPassword() ?: $config->getTransportOption('pass', 'guest')
+ );
+
+ return new RabbitMqStompDriver($factory->createContext(), $config, $collection, $managementClient);
+ }
}
diff --git a/pkg/enqueue/Client/DriverFactoryInterface.php b/pkg/enqueue/Client/DriverFactoryInterface.php
index 6a558b7e2..698ad05a4 100644
--- a/pkg/enqueue/Client/DriverFactoryInterface.php
+++ b/pkg/enqueue/Client/DriverFactoryInterface.php
@@ -6,5 +6,5 @@
interface DriverFactoryInterface
{
- public function create(ConnectionFactory $factory, string $dsn, array $config): DriverInterface;
+ public function create(ConnectionFactory $factory, Config $config, RouteCollection $collection): DriverInterface;
}
diff --git a/pkg/enqueue/Client/DriverInterface.php b/pkg/enqueue/Client/DriverInterface.php
index f8b13d06a..9d1dde679 100644
--- a/pkg/enqueue/Client/DriverInterface.php
+++ b/pkg/enqueue/Client/DriverInterface.php
@@ -15,9 +15,9 @@ public function createTransportMessage(Message $message): InteropMessage;
public function createClientMessage(InteropMessage $message): Message;
- public function sendToRouter(Message $message): void;
+ public function sendToRouter(Message $message): DriverSendResult;
- public function sendToProcessor(Message $message): void;
+ public function sendToProcessor(Message $message): DriverSendResult;
public function createQueue(string $queueName, bool $prefix = true): InteropQueue;
@@ -27,7 +27,7 @@ public function createRouteQueue(Route $route): InteropQueue;
* Prepare broker for work.
* Creates all required queues, exchanges, topics, bindings etc.
*/
- public function setupBroker(LoggerInterface $logger = null): void;
+ public function setupBroker(?LoggerInterface $logger = null): void;
public function getConfig(): Config;
diff --git a/pkg/enqueue/Client/DriverPreSendExtensionInterface.php b/pkg/enqueue/Client/DriverPreSendExtensionInterface.php
new file mode 100644
index 000000000..fd95c9328
--- /dev/null
+++ b/pkg/enqueue/Client/DriverPreSendExtensionInterface.php
@@ -0,0 +1,8 @@
+transportDestination = $transportDestination;
+ $this->transportMessage = $transportMessage;
+ }
+
+ public function getTransportDestination(): Destination
+ {
+ return $this->transportDestination;
+ }
+
+ public function getTransportMessage(): TransportMessage
+ {
+ return $this->transportMessage;
+ }
+}
diff --git a/pkg/enqueue/Client/EmptyExtensionTrait.php b/pkg/enqueue/Client/EmptyExtensionTrait.php
deleted file mode 100644
index 2b4f97634..000000000
--- a/pkg/enqueue/Client/EmptyExtensionTrait.php
+++ /dev/null
@@ -1,22 +0,0 @@
-prepareBody($context->getMessage());
@@ -34,10 +32,7 @@ private function prepareBody(Message $message): void
// only array of scalars is allowed.
array_walk_recursive($body, function ($value) {
if (!is_scalar($value) && null !== $value) {
- throw new \LogicException(sprintf(
- 'The message\'s body must be an array of scalars. Found not scalar in the array: %s',
- is_object($value) ? get_class($value) : gettype($value)
- ));
+ throw new \LogicException(sprintf('The message\'s body must be an array of scalars. Found not scalar in the array: %s', is_object($value) ? $value::class : gettype($value)));
}
});
@@ -47,10 +42,7 @@ private function prepareBody(Message $message): void
$contentType = $contentType ?: 'application/json';
$body = JSON::encode($body);
} else {
- throw new \InvalidArgumentException(sprintf(
- 'The message\'s body must be either null, scalar, array or object (implements \JsonSerializable). Got: %s',
- is_object($body) ? get_class($body) : gettype($body)
- ));
+ throw new \InvalidArgumentException(sprintf('The message\'s body must be either null, scalar, array or object (implements \JsonSerializable). Got: %s', is_object($body) ? $body::class : gettype($body)));
}
$message->setContentType($contentType);
diff --git a/pkg/enqueue/Client/ExtensionInterface.php b/pkg/enqueue/Client/ExtensionInterface.php
index a0b413d69..596b1b9af 100644
--- a/pkg/enqueue/Client/ExtensionInterface.php
+++ b/pkg/enqueue/Client/ExtensionInterface.php
@@ -2,13 +2,6 @@
namespace Enqueue\Client;
-interface ExtensionInterface
+interface ExtensionInterface extends PreSendEventExtensionInterface, PreSendCommandExtensionInterface, DriverPreSendExtensionInterface, PostSendExtensionInterface
{
- public function onPreSendEvent(PreSend $context): void;
-
- public function onPreSendCommand(PreSend $context): void;
-
- public function onDriverPreSend(DriverPreSend $context): void;
-
- public function onPostSend(PostSend $context): void;
}
diff --git a/pkg/enqueue/Client/Message.php b/pkg/enqueue/Client/Message.php
index 6f1186dcc..7e51ea10d 100644
--- a/pkg/enqueue/Client/Message.php
+++ b/pkg/enqueue/Client/Message.php
@@ -7,12 +7,12 @@ class Message
/**
* @const string
*/
- const SCOPE_MESSAGE_BUS = 'enqueue.scope.message_bus';
+ public const SCOPE_MESSAGE_BUS = 'enqueue.scope.message_bus';
/**
* @const string
*/
- const SCOPE_APP = 'enqueue.scope.app';
+ public const SCOPE_APP = 'enqueue.scope.app';
/**
* @var string|null
@@ -88,7 +88,7 @@ public function __construct($body = '', array $properties = [], array $headers =
}
/**
- * @return null|string
+ * @return string|null
*/
public function getBody()
{
@@ -96,7 +96,7 @@ public function getBody()
}
/**
- * @param null|string|int|float|array|\JsonSerializable $body
+ * @param string|int|float|array|\JsonSerializable|null $body
*/
public function setBody($body)
{
@@ -256,10 +256,8 @@ public function getHeaders()
}
/**
- * @param string $name
- * @param mixed $default
- *
- * @return mixed
+ * @param string $name
+ * @param mixed|null $default
*/
public function getHeader($name, $default = null)
{
@@ -268,16 +266,12 @@ public function getHeader($name, $default = null)
/**
* @param string $name
- * @param mixed $value
*/
public function setHeader($name, $value)
{
$this->headers[$name] = $value;
}
- /**
- * @param array $headers
- */
public function setHeaders(array $headers)
{
$this->headers = $headers;
@@ -291,19 +285,14 @@ public function getProperties()
return $this->properties;
}
- /**
- * @param array $properties
- */
public function setProperties(array $properties)
{
$this->properties = $properties;
}
/**
- * @param string $name
- * @param mixed $default
- *
- * @return mixed
+ * @param string $name
+ * @param mixed|null $default
*/
public function getProperty($name, $default = null)
{
@@ -312,7 +301,6 @@ public function getProperty($name, $default = null)
/**
* @param string $name
- * @param mixed $value
*/
public function setProperty($name, $value)
{
diff --git a/pkg/enqueue/Client/MessagePriority.php b/pkg/enqueue/Client/MessagePriority.php
index efa658c14..e14be9a7d 100644
--- a/pkg/enqueue/Client/MessagePriority.php
+++ b/pkg/enqueue/Client/MessagePriority.php
@@ -4,9 +4,9 @@
class MessagePriority
{
- const VERY_LOW = 'enqueue.message_queue.client.very_low_message_priority';
- const LOW = 'enqueue.message_queue.client.low_message_priority';
- const NORMAL = 'enqueue.message_queue.client.normal_message_priority';
- const HIGH = 'enqueue.message_queue.client.high_message_priority';
- const VERY_HIGH = 'enqueue.message_queue.client.very_high_message_priority';
+ public const VERY_LOW = 'enqueue.message_queue.client.very_low_message_priority';
+ public const LOW = 'enqueue.message_queue.client.low_message_priority';
+ public const NORMAL = 'enqueue.message_queue.client.normal_message_priority';
+ public const HIGH = 'enqueue.message_queue.client.high_message_priority';
+ public const VERY_HIGH = 'enqueue.message_queue.client.very_high_message_priority';
}
diff --git a/pkg/enqueue/Client/PostSend.php b/pkg/enqueue/Client/PostSend.php
index 1c5ab9d04..5d9526ea4 100644
--- a/pkg/enqueue/Client/PostSend.php
+++ b/pkg/enqueue/Client/PostSend.php
@@ -2,6 +2,9 @@
namespace Enqueue\Client;
+use Interop\Queue\Destination;
+use Interop\Queue\Message as TransportMessage;
+
final class PostSend
{
private $message;
@@ -10,11 +13,22 @@ final class PostSend
private $driver;
- public function __construct(Message $message, ProducerInterface $producer, DriverInterface $driver)
- {
+ private $transportDestination;
+
+ private $transportMessage;
+
+ public function __construct(
+ Message $message,
+ ProducerInterface $producer,
+ DriverInterface $driver,
+ Destination $transportDestination,
+ TransportMessage $transportMessage,
+ ) {
$this->message = $message;
$this->producer = $producer;
$this->driver = $driver;
+ $this->transportDestination = $transportDestination;
+ $this->transportMessage = $transportMessage;
}
public function getMessage(): Message
@@ -32,6 +46,16 @@ public function getDriver(): DriverInterface
return $this->driver;
}
+ public function getTransportDestination(): Destination
+ {
+ return $this->transportDestination;
+ }
+
+ public function getTransportMessage(): TransportMessage
+ {
+ return $this->transportMessage;
+ }
+
public function isEvent(): bool
{
return (bool) $this->message->getProperty(Config::TOPIC);
diff --git a/pkg/enqueue/Client/PostSendExtensionInterface.php b/pkg/enqueue/Client/PostSendExtensionInterface.php
new file mode 100644
index 000000000..dd3ca8b71
--- /dev/null
+++ b/pkg/enqueue/Client/PostSendExtensionInterface.php
@@ -0,0 +1,8 @@
+message = $message;
$this->commandOrTopic = $commandOrTopic;
@@ -48,7 +48,7 @@ public function changeTopic(string $newTopic): void
$this->commandOrTopic = $newTopic;
}
- public function changeBody($body, string $contentType = null): void
+ public function changeBody($body, ?string $contentType = null): void
{
$this->message->setBody($body);
diff --git a/pkg/enqueue/Client/PreSendCommandExtensionInterface.php b/pkg/enqueue/Client/PreSendCommandExtensionInterface.php
new file mode 100644
index 000000000..cefec097f
--- /dev/null
+++ b/pkg/enqueue/Client/PreSendCommandExtensionInterface.php
@@ -0,0 +1,11 @@
+driver = $driver;
$this->rpcFactory = $rpcFactory;
@@ -97,10 +97,7 @@ public function sendCommand(string $command, $message, bool $needReply = false):
private function doSend(Message $message): void
{
if (false === is_string($message->getBody())) {
- throw new \LogicException(sprintf(
- 'The message body must be string at this stage, got "%s". Make sure you passed string as message or there is an extension that converts custom input to string.',
- is_object($message->getBody()) ? get_class($message->getBody()) : gettype($message->getBody())
- ));
+ throw new \LogicException(sprintf('The message body must be string at this stage, got "%s". Make sure you passed string as message or there is an extension that converts custom input to string.', is_object($message->getBody()) ? get_class($message->getBody()) : gettype($message->getBody())));
}
if ($message->getProperty(Config::PROCESSOR)) {
@@ -118,13 +115,13 @@ private function doSend(Message $message): void
$this->extension->onDriverPreSend(new DriverPreSend($message, $this, $this->driver));
if (Message::SCOPE_MESSAGE_BUS == $message->getScope()) {
- $this->driver->sendToRouter($message);
+ $result = $this->driver->sendToRouter($message);
} elseif (Message::SCOPE_APP == $message->getScope()) {
- $this->driver->sendToProcessor($message);
+ $result = $this->driver->sendToProcessor($message);
} else {
throw new \LogicException(sprintf('The message scope "%s" is not supported.', $message->getScope()));
}
- $this->extension->onPostSend(new PostSend($message, $this, $this->driver));
+ $this->extension->onPostSend(new PostSend($message, $this, $this->driver, $result->getTransportDestination(), $result->getTransportMessage()));
}
}
diff --git a/pkg/enqueue/Client/ProducerInterface.php b/pkg/enqueue/Client/ProducerInterface.php
index 1c7b056cf..3c884808a 100644
--- a/pkg/enqueue/Client/ProducerInterface.php
+++ b/pkg/enqueue/Client/ProducerInterface.php
@@ -10,6 +10,8 @@ interface ProducerInterface
* The message could be pretty much everything as long as you have a client extension that transforms a body to string on onPreSendEvent.
*
* @param string|array|Message $message
+ *
+ * @throws \Exception
*/
public function sendEvent(string $topic, $message): void;
@@ -18,6 +20,8 @@ public function sendEvent(string $topic, $message): void;
* The promise is returned if needReply argument is true.
*
* @param string|array|Message $message
+ *
+ * @throws \Exception
*/
public function sendCommand(string $command, $message, bool $needReply = false): ?Promise;
}
diff --git a/pkg/enqueue/Client/Resources.php b/pkg/enqueue/Client/Resources.php
index 56fc76472..a5cc6847c 100644
--- a/pkg/enqueue/Client/Resources.php
+++ b/pkg/enqueue/Client/Resources.php
@@ -12,6 +12,7 @@
use Enqueue\Client\Driver\RabbitMqStompDriver;
use Enqueue\Client\Driver\RdKafkaDriver;
use Enqueue\Client\Driver\RedisDriver;
+use Enqueue\Client\Driver\SnsQsDriver;
use Enqueue\Client\Driver\SqsDriver;
use Enqueue\Client\Driver\StompDriver;
@@ -25,7 +26,7 @@ final class Resources
*
* @var array
*/
- private static $knownDrivers = null;
+ private static $knownDrivers;
private function __construct()
{
@@ -37,7 +38,7 @@ public static function getAvailableDrivers(): array
$availableMap = [];
foreach ($map as $item) {
- if (class_exists($item['factoryClass'])) {
+ if (class_exists($item['driverClass'])) {
$availableMap[] = $item;
}
}
@@ -52,67 +53,79 @@ public static function getKnownDrivers(): array
$map[] = [
'schemes' => ['amqp', 'amqps'],
- 'factoryClass' => AmqpDriver::class,
+ 'driverClass' => AmqpDriver::class,
'requiredSchemeExtensions' => [],
'packages' => ['enqueue/enqueue', 'enqueue/amqp-bunny'],
];
$map[] = [
'schemes' => ['amqp', 'amqps'],
- 'factoryClass' => RabbitMqDriver::class,
+ 'driverClass' => RabbitMqDriver::class,
'requiredSchemeExtensions' => ['rabbitmq'],
'packages' => ['enqueue/enqueue', 'enqueue/amqp-bunny'],
];
$map[] = [
'schemes' => ['file'],
- 'factoryClass' => FsDriver::class,
+ 'driverClass' => FsDriver::class,
'requiredSchemeExtensions' => [],
'packages' => ['enqueue/enqueue', 'enqueue/fs'],
];
$map[] = [
'schemes' => ['null'],
- 'factoryClass' => GenericDriver::class,
+ 'driverClass' => GenericDriver::class,
'requiredSchemeExtensions' => [],
'packages' => ['enqueue/enqueue', 'enqueue/null'],
];
$map[] = [
'schemes' => ['gps'],
- 'factoryClass' => GpsDriver::class,
+ 'driverClass' => GpsDriver::class,
'requiredSchemeExtensions' => [],
'packages' => ['enqueue/enqueue', 'enqueue/gps'],
];
$map[] = [
- 'schemes' => ['redis'],
- 'factoryClass' => RedisDriver::class,
+ 'schemes' => ['redis', 'rediss'],
+ 'driverClass' => RedisDriver::class,
'requiredSchemeExtensions' => [],
'packages' => ['enqueue/enqueue', 'enqueue/redis'],
];
$map[] = [
'schemes' => ['sqs'],
- 'factoryClass' => SqsDriver::class,
+ 'driverClass' => SqsDriver::class,
'requiredSchemeExtensions' => [],
'packages' => ['enqueue/enqueue', 'enqueue/sqs'],
];
+ $map[] = [
+ 'schemes' => ['sns'],
+ 'driverClass' => GenericDriver::class,
+ 'requiredSchemeExtensions' => [],
+ 'packages' => ['enqueue/enqueue', 'enqueue/sns'],
+ ];
+ $map[] = [
+ 'schemes' => ['snsqs'],
+ 'driverClass' => SnsQsDriver::class,
+ 'requiredSchemeExtensions' => [],
+ 'packages' => ['enqueue/enqueue', 'enqueue/sqs', 'enqueue/sns', 'enqueue/snsqs'],
+ ];
$map[] = [
'schemes' => ['stomp'],
- 'factoryClass' => StompDriver::class,
+ 'driverClass' => StompDriver::class,
'requiredSchemeExtensions' => [],
'packages' => ['enqueue/enqueue', 'enqueue/stomp'],
];
$map[] = [
'schemes' => ['stomp'],
- 'factoryClass' => RabbitMqStompDriver::class,
+ 'driverClass' => RabbitMqStompDriver::class,
'requiredSchemeExtensions' => ['rabbitmq'],
'packages' => ['enqueue/enqueue', 'enqueue/stomp'],
];
$map[] = [
'schemes' => ['kafka', 'rdkafka'],
- 'factoryClass' => RdKafkaDriver::class,
+ 'driverClass' => RdKafkaDriver::class,
'requiredSchemeExtensions' => [],
'packages' => ['enqueue/enqueue', 'enqueue/rdkafka'],
];
$map[] = [
'schemes' => ['mongodb'],
- 'factoryClass' => MongodbDriver::class,
+ 'driverClass' => MongodbDriver::class,
'requiredSchemeExtensions' => [],
'packages' => ['enqueue/enqueue', 'enqueue/mongodb'],
];
@@ -132,19 +145,19 @@ public static function getKnownDrivers(): array
'sqlite3',
'sqlite',
],
- 'factoryClass' => DbalDriver::class,
+ 'driverClass' => DbalDriver::class,
'requiredSchemeExtensions' => [],
'package' => ['enqueue/enqueue', 'enqueue/dbal'],
];
$map[] = [
'schemes' => ['gearman'],
- 'factoryClass' => GenericDriver::class,
+ 'driverClass' => GenericDriver::class,
'requiredSchemeExtensions' => [],
'package' => ['enqueue/enqueue', 'enqueue/gearman'],
];
$map[] = [
'schemes' => ['beanstalk'],
- 'factoryClass' => GenericDriver::class,
+ 'driverClass' => GenericDriver::class,
'requiredSchemeExtensions' => [],
'package' => ['enqueue/enqueue', 'enqueue/pheanstalk'],
];
@@ -173,7 +186,7 @@ public static function addDriver(string $driverClass, array $schemes, array $req
self::getKnownDrivers();
self::$knownDrivers[] = [
'schemes' => $schemes,
- 'factoryClass' => $driverClass,
+ 'driverClass' => $driverClass,
'requiredSchemeExtensions' => $requiredExtensions,
'packages' => $packages,
];
diff --git a/pkg/enqueue/Client/Route.php b/pkg/enqueue/Client/Route.php
index 5c98fa6b8..8b9e31e36 100644
--- a/pkg/enqueue/Client/Route.php
+++ b/pkg/enqueue/Client/Route.php
@@ -4,9 +4,9 @@
final class Route
{
- const TOPIC = 'enqueue.client.topic_route';
+ public const TOPIC = 'enqueue.client.topic_route';
- const COMMAND = 'enqueue.client.command_route';
+ public const COMMAND = 'enqueue.client.command_route';
/**
* @var string
@@ -32,7 +32,7 @@ public function __construct(
string $source,
string $sourceType,
string $processor,
- array $options = []
+ array $options = [],
) {
$this->source = $source;
$this->sourceType = $sourceType;
diff --git a/pkg/enqueue/Client/RouterProcessor.php b/pkg/enqueue/Client/RouterProcessor.php
index c4832fd0f..c441ceb8b 100644
--- a/pkg/enqueue/Client/RouterProcessor.php
+++ b/pkg/enqueue/Client/RouterProcessor.php
@@ -9,6 +9,11 @@
final class RouterProcessor implements Processor
{
+ /**
+ * compatibility with 0.8x.
+ */
+ private const COMMAND_TOPIC_08X = '__command__';
+
/**
* @var DriverInterface
*/
@@ -21,6 +26,17 @@ public function __construct(DriverInterface $driver)
public function process(InteropMessage $message, Context $context): Result
{
+ // compatibility with 0.8x
+ if (self::COMMAND_TOPIC_08X === $message->getProperty(Config::TOPIC)) {
+ $clientMessage = $this->driver->createClientMessage($message);
+ $clientMessage->setProperty(Config::TOPIC, null);
+
+ $this->driver->sendToProcessor($clientMessage);
+
+ return Result::ack('Legacy 0.8x message routed to processor');
+ }
+ // compatibility with 0.8x
+
if ($message->getProperty(Config::COMMAND)) {
return Result::reject(sprintf(
'Unexpected command "%s" got. Command must not go to the router.',
diff --git a/pkg/enqueue/Client/TopicSubscriberInterface.php b/pkg/enqueue/Client/TopicSubscriberInterface.php
index 634a7ace2..849a7827f 100644
--- a/pkg/enqueue/Client/TopicSubscriberInterface.php
+++ b/pkg/enqueue/Client/TopicSubscriberInterface.php
@@ -15,10 +15,22 @@ interface TopicSubscriberInterface
*
* or
*
- * ['aTopicName' => [
- * 'processor' => 'processor',
+ * [
+ * [
+ * 'topic' => 'aTopicName',
+ * 'processor' => 'fooProcessor',
* 'queue' => 'a_client_queue_name',
- * ]]
+ *
+ * 'aCustomOption' => 'aVal',
+ * ],
+ * [
+ * 'topic' => 'anotherTopicName',
+ * 'processor' => 'barProcessor',
+ * 'queue' => 'a_client_queue_name',
+ *
+ * 'aCustomOption' => 'aVal',
+ * ],
+ * ]
*
* Note: If you set prefix_queue to true then the queue is used as is and therefor the driver is not used to prepare a transport queue name.
* It is possible to pass other options, they could be accessible on a route instance through options.
diff --git a/pkg/enqueue/Client/TraceableProducer.php b/pkg/enqueue/Client/TraceableProducer.php
index 86ff9f8c6..b0bd613c3 100644
--- a/pkg/enqueue/Client/TraceableProducer.php
+++ b/pkg/enqueue/Client/TraceableProducer.php
@@ -71,7 +71,7 @@ public function clearTraces(): void
$this->traces = [];
}
- private function collectTrace(string $topic = null, string $command = null, $message): void
+ private function collectTrace(?string $topic, ?string $command, $message): void
{
$trace = [
'topic' => $topic,
@@ -85,6 +85,7 @@ private function collectTrace(string $topic = null, string $command = null, $mes
'timestamp' => null,
'contentType' => null,
'messageId' => null,
+ 'sentAt' => (new \DateTime())->format('Y-m-d H:i:s.u'),
];
if ($message instanceof Message) {
diff --git a/pkg/enqueue/ConnectionFactoryFactory.php b/pkg/enqueue/ConnectionFactoryFactory.php
index 48c7f3d7f..d23518c1b 100644
--- a/pkg/enqueue/ConnectionFactoryFactory.php
+++ b/pkg/enqueue/ConnectionFactoryFactory.php
@@ -21,7 +21,7 @@ public function create($config): ConnectionFactory
throw new \InvalidArgumentException('The config must have dsn key set.');
}
- $dsn = new Dsn($config['dsn']);
+ $dsn = Dsn::parseFirst($config['dsn']);
if ($factoryClass = $this->findFactoryClass($dsn, Resources::getAvailableConnections())) {
return new $factoryClass(1 === count($config) ? $config['dsn'] : $config);
@@ -29,18 +29,10 @@ public function create($config): ConnectionFactory
$knownConnections = Resources::getKnownConnections();
if ($factoryClass = $this->findFactoryClass($dsn, $knownConnections)) {
- throw new \LogicException(sprintf(
- 'To use given scheme "%s" a package has to be installed. Run "composer req %s" to add it.',
- $dsn->getScheme(),
- $knownConnections[$factoryClass]['package']
- ));
+ throw new \LogicException(sprintf('To use given scheme "%s" a package has to be installed. Run "composer req %s" to add it.', $dsn->getScheme(), $knownConnections[$factoryClass]['package']));
}
- throw new \LogicException(sprintf(
- 'A given scheme "%s" is not supported. Maybe it is a custom connection, make sure you registered it with "%s::addConnection".',
- $dsn->getScheme(),
- Resources::class
- ));
+ throw new \LogicException(sprintf('A given scheme "%s" is not supported. Maybe it is a custom connection, make sure you registered it with "%s::addConnection".', $dsn->getScheme(), Resources::class));
}
private function findFactoryClass(Dsn $dsn, array $factories): ?string
diff --git a/pkg/enqueue/ConnectionFactoryFactoryInterface.php b/pkg/enqueue/ConnectionFactoryFactoryInterface.php
index d55808cdb..f4ca4a6d3 100644
--- a/pkg/enqueue/ConnectionFactoryFactoryInterface.php
+++ b/pkg/enqueue/ConnectionFactoryFactoryInterface.php
@@ -13,7 +13,6 @@ interface ConnectionFactoryFactoryInterface
* The other array options are treated as default values.
* Options from DSN overwrite them.
*
- *
* @param string|array $config
*
* @throws \InvalidArgumentException if invalid config provided
diff --git a/pkg/enqueue/Consumption/CallbackProcessor.php b/pkg/enqueue/Consumption/CallbackProcessor.php
index 988b76529..d15978fcb 100644
--- a/pkg/enqueue/Consumption/CallbackProcessor.php
+++ b/pkg/enqueue/Consumption/CallbackProcessor.php
@@ -13,17 +13,11 @@ class CallbackProcessor implements Processor
*/
private $callback;
- /**
- * @param callable $callback
- */
public function __construct(callable $callback)
{
$this->callback = $callback;
}
- /**
- * {@inheritdoc}
- */
public function process(InteropMessage $message, Context $context)
{
return call_user_func($this->callback, $message, $context);
diff --git a/pkg/enqueue/Consumption/ChainExtension.php b/pkg/enqueue/Consumption/ChainExtension.php
index 6911b5b6b..83b4eba3a 100644
--- a/pkg/enqueue/Consumption/ChainExtension.php
+++ b/pkg/enqueue/Consumption/ChainExtension.php
@@ -117,7 +117,7 @@ public function __construct(array $extensions)
}
if (false == $extensionValid) {
- throw new \LogicException('Invalid extension given');
+ throw new \LogicException(sprintf('Invalid extension given %s', $extension::class));
}
});
}
diff --git a/pkg/enqueue/Consumption/Context/End.php b/pkg/enqueue/Consumption/Context/End.php
index 467f6d38c..07853b3d3 100644
--- a/pkg/enqueue/Consumption/Context/End.php
+++ b/pkg/enqueue/Consumption/Context/End.php
@@ -27,12 +27,23 @@ final class End
*/
private $logger;
- public function __construct(Context $context, int $startTime, int $endTime, LoggerInterface $logger)
- {
+ /**
+ * @var int
+ */
+ private $exitStatus;
+
+ public function __construct(
+ Context $context,
+ int $startTime,
+ int $endTime,
+ LoggerInterface $logger,
+ ?int $exitStatus = null,
+ ) {
$this->context = $context;
$this->logger = $logger;
$this->startTime = $startTime;
$this->endTime = $endTime;
+ $this->exitStatus = $exitStatus;
}
public function getContext(): Context
@@ -60,4 +71,9 @@ public function getEndTime(): int
{
return $this->startTime;
}
+
+ public function getExitStatus(): ?int
+ {
+ return $this->exitStatus;
+ }
}
diff --git a/pkg/enqueue/Consumption/Context/MessageReceived.php b/pkg/enqueue/Consumption/Context/MessageReceived.php
index ad6b6b969..35abf1ca8 100644
--- a/pkg/enqueue/Consumption/Context/MessageReceived.php
+++ b/pkg/enqueue/Consumption/Context/MessageReceived.php
@@ -52,7 +52,7 @@ public function __construct(
Message $message,
Processor $processor,
int $receivedAt,
- LoggerInterface $logger
+ LoggerInterface $logger,
) {
$this->context = $context;
$this->consumer = $consumer;
diff --git a/pkg/enqueue/Consumption/Context/MessageResult.php b/pkg/enqueue/Consumption/Context/MessageResult.php
index fccda66b2..4fa8f7de0 100644
--- a/pkg/enqueue/Consumption/Context/MessageResult.php
+++ b/pkg/enqueue/Consumption/Context/MessageResult.php
@@ -3,6 +3,7 @@
namespace Enqueue\Consumption\Context;
use Enqueue\Consumption\Result;
+use Interop\Queue\Consumer;
use Interop\Queue\Context;
use Interop\Queue\Message;
use Psr\Log\LoggerInterface;
@@ -14,6 +15,11 @@ final class MessageResult
*/
private $context;
+ /**
+ * @var Consumer
+ */
+ private $consumer;
+
/**
* @var Message
*/
@@ -34,9 +40,10 @@ final class MessageResult
*/
private $logger;
- public function __construct(Context $context, Message $message, $result, int $receivedAt, LoggerInterface $logger)
+ public function __construct(Context $context, Consumer $consumer, Message $message, $result, int $receivedAt, LoggerInterface $logger)
{
$this->context = $context;
+ $this->consumer = $consumer;
$this->message = $message;
$this->logger = $logger;
$this->result = $result;
@@ -48,6 +55,11 @@ public function getContext(): Context
return $this->context;
}
+ public function getConsumer(): Consumer
+ {
+ return $this->consumer;
+ }
+
public function getMessage(): Message
{
return $this->message;
@@ -64,7 +76,7 @@ public function getReceivedAt(): int
}
/**
- * @return Result|null|object|string
+ * @return Result|object|string|null
*/
public function getResult()
{
diff --git a/pkg/enqueue/Consumption/Context/PostConsume.php b/pkg/enqueue/Consumption/Context/PostConsume.php
index 0add00336..a6f1d8375 100644
--- a/pkg/enqueue/Consumption/Context/PostConsume.php
+++ b/pkg/enqueue/Consumption/Context/PostConsume.php
@@ -43,6 +43,11 @@ final class PostConsume
*/
private $executionInterrupted;
+ /**
+ * @var int
+ */
+ private $exitStatus;
+
public function __construct(Context $context, SubscriptionConsumer $subscriptionConsumer, int $receivedMessagesCount, int $cycle, int $startTime, LoggerInterface $logger)
{
$this->context = $context;
@@ -85,13 +90,19 @@ public function getLogger(): LoggerInterface
return $this->logger;
}
+ public function getExitStatus(): ?int
+ {
+ return $this->exitStatus;
+ }
+
public function isExecutionInterrupted(): bool
{
return $this->executionInterrupted;
}
- public function interruptExecution(): void
+ public function interruptExecution(?int $exitStatus = null): void
{
+ $this->exitStatus = $exitStatus;
$this->executionInterrupted = true;
}
}
diff --git a/pkg/enqueue/Consumption/Context/PostMessageReceived.php b/pkg/enqueue/Consumption/Context/PostMessageReceived.php
index 423830e3d..23df2c849 100644
--- a/pkg/enqueue/Consumption/Context/PostMessageReceived.php
+++ b/pkg/enqueue/Consumption/Context/PostMessageReceived.php
@@ -45,13 +45,18 @@ final class PostMessageReceived
*/
private $executionInterrupted;
+ /**
+ * @var int
+ */
+ private $exitStatus;
+
public function __construct(
Context $context,
Consumer $consumer,
Message $message,
$result,
int $receivedAt,
- LoggerInterface $logger
+ LoggerInterface $logger,
) {
$this->context = $context;
$this->consumer = $consumer;
@@ -89,20 +94,26 @@ public function getReceivedAt(): int
}
/**
- * @return Result|null|object|string
+ * @return Result|object|string|null
*/
public function getResult()
{
return $this->result;
}
+ public function getExitStatus(): ?int
+ {
+ return $this->exitStatus;
+ }
+
public function isExecutionInterrupted(): bool
{
return $this->executionInterrupted;
}
- public function interruptExecution(): void
+ public function interruptExecution(?int $exitStatus = null): void
{
+ $this->exitStatus = $exitStatus;
$this->executionInterrupted = true;
}
}
diff --git a/pkg/enqueue/Consumption/Context/PreConsume.php b/pkg/enqueue/Consumption/Context/PreConsume.php
index a6d83d534..77cc7d030 100644
--- a/pkg/enqueue/Consumption/Context/PreConsume.php
+++ b/pkg/enqueue/Consumption/Context/PreConsume.php
@@ -43,6 +43,11 @@ final class PreConsume
*/
private $executionInterrupted;
+ /**
+ * @var int
+ */
+ private $exitStatus;
+
public function __construct(Context $context, SubscriptionConsumer $subscriptionConsumer, LoggerInterface $logger, int $cycle, int $receiveTimeout, int $startTime)
{
$this->context = $context;
@@ -85,13 +90,19 @@ public function getStartTime(): int
return $this->startTime;
}
+ public function getExitStatus(): ?int
+ {
+ return $this->exitStatus;
+ }
+
public function isExecutionInterrupted(): bool
{
return $this->executionInterrupted;
}
- public function interruptExecution(): void
+ public function interruptExecution(?int $exitStatus = null): void
{
+ $this->exitStatus = $exitStatus;
$this->executionInterrupted = true;
}
}
diff --git a/pkg/enqueue/Consumption/Context/ProcessorException.php b/pkg/enqueue/Consumption/Context/ProcessorException.php
index 139bd6704..329b13d93 100644
--- a/pkg/enqueue/Consumption/Context/ProcessorException.php
+++ b/pkg/enqueue/Consumption/Context/ProcessorException.php
@@ -3,6 +3,7 @@
namespace Enqueue\Consumption\Context;
use Enqueue\Consumption\Result;
+use Interop\Queue\Consumer;
use Interop\Queue\Context;
use Interop\Queue\Message;
use Psr\Log\LoggerInterface;
@@ -14,13 +15,18 @@ final class ProcessorException
*/
private $context;
+ /**
+ * @var Consumer
+ */
+ private $consumer;
+
/**
* @var Message
*/
private $message;
/**
- * @var \Exception
+ * @var \Throwable
*/
private $exception;
@@ -38,9 +44,10 @@ final class ProcessorException
*/
private $logger;
- public function __construct(Context $context, Message $message, \Exception $exception, int $receivedAt, LoggerInterface $logger)
+ public function __construct(Context $context, Consumer $consumer, Message $message, \Throwable $exception, int $receivedAt, LoggerInterface $logger)
{
$this->context = $context;
+ $this->consumer = $consumer;
$this->message = $message;
$this->exception = $exception;
$this->logger = $logger;
@@ -52,12 +59,17 @@ public function getContext(): Context
return $this->context;
}
+ public function getConsumer(): Consumer
+ {
+ return $this->consumer;
+ }
+
public function getMessage(): Message
{
return $this->message;
}
- public function getException(): \Exception
+ public function getException(): \Throwable
{
return $this->exception;
}
diff --git a/pkg/enqueue/Consumption/Context/Start.php b/pkg/enqueue/Consumption/Context/Start.php
index cd9f2108e..84db29c44 100644
--- a/pkg/enqueue/Consumption/Context/Start.php
+++ b/pkg/enqueue/Consumption/Context/Start.php
@@ -38,6 +38,11 @@ final class Start
*/
private $executionInterrupted;
+ /**
+ * @var int
+ */
+ private $exitStatus;
+
/**
* @param BoundProcessor[] $processors
*/
@@ -105,13 +110,19 @@ public function changeBoundProcessors(array $processors): void
});
}
+ public function getExitStatus(): ?int
+ {
+ return $this->exitStatus;
+ }
+
public function isExecutionInterrupted(): bool
{
return $this->executionInterrupted;
}
- public function interruptExecution(): void
+ public function interruptExecution(?int $exitStatus = null): void
{
+ $this->exitStatus = $exitStatus;
$this->executionInterrupted = true;
}
}
diff --git a/pkg/enqueue/Consumption/Exception/InvalidArgumentException.php b/pkg/enqueue/Consumption/Exception/InvalidArgumentException.php
index da6015d27..89a2f4ca7 100644
--- a/pkg/enqueue/Consumption/Exception/InvalidArgumentException.php
+++ b/pkg/enqueue/Consumption/Exception/InvalidArgumentException.php
@@ -5,7 +5,6 @@
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
/**
- * @param mixed $argument
* @param string $class
*
* @throws static
@@ -13,11 +12,7 @@ class InvalidArgumentException extends \InvalidArgumentException implements Exce
public static function assertInstanceOf($argument, $class)
{
if (false == $argument instanceof $class) {
- throw new static(sprintf(
- 'The argument must be an instance of %s but got %s.',
- $class,
- is_object($argument) ? get_class($argument) : gettype($argument)
- ));
+ throw new self(sprintf('The argument must be an instance of %s but got %s.', $class, is_object($argument) ? $argument::class : gettype($argument)));
}
}
}
diff --git a/pkg/enqueue/Consumption/Extension/ExitStatusExtension.php b/pkg/enqueue/Consumption/Extension/ExitStatusExtension.php
new file mode 100644
index 000000000..a43071241
--- /dev/null
+++ b/pkg/enqueue/Consumption/Extension/ExitStatusExtension.php
@@ -0,0 +1,24 @@
+exitStatus = $context->getExitStatus();
+ }
+
+ public function getExitStatus(): ?int
+ {
+ return $this->exitStatus;
+ }
+}
diff --git a/pkg/enqueue/Consumption/Extension/LimitConsumedMessagesExtension.php b/pkg/enqueue/Consumption/Extension/LimitConsumedMessagesExtension.php
index e89957a72..0dc6feceb 100644
--- a/pkg/enqueue/Consumption/Extension/LimitConsumedMessagesExtension.php
+++ b/pkg/enqueue/Consumption/Extension/LimitConsumedMessagesExtension.php
@@ -20,9 +20,6 @@ class LimitConsumedMessagesExtension implements PreConsumeExtensionInterface, Po
*/
protected $messageConsumed;
- /**
- * @param int $messageLimit
- */
public function __construct(int $messageLimit)
{
$this->messageLimit = $messageLimit;
diff --git a/pkg/enqueue/Consumption/Extension/LimitConsumerMemoryExtension.php b/pkg/enqueue/Consumption/Extension/LimitConsumerMemoryExtension.php
index 13d4a2898..7edbf232c 100644
--- a/pkg/enqueue/Consumption/Extension/LimitConsumerMemoryExtension.php
+++ b/pkg/enqueue/Consumption/Extension/LimitConsumerMemoryExtension.php
@@ -23,10 +23,7 @@ class LimitConsumerMemoryExtension implements PreConsumeExtensionInterface, Post
public function __construct($memoryLimit)
{
if (false == is_int($memoryLimit)) {
- throw new \InvalidArgumentException(sprintf(
- 'Expected memory limit is int but got: "%s"',
- is_object($memoryLimit) ? get_class($memoryLimit) : gettype($memoryLimit)
- ));
+ throw new \InvalidArgumentException(sprintf('Expected memory limit is int but got: "%s"', is_object($memoryLimit) ? $memoryLimit::class : gettype($memoryLimit)));
}
$this->memoryLimit = $memoryLimit * 1024 * 1024;
diff --git a/pkg/enqueue/Consumption/Extension/LimitConsumptionTimeExtension.php b/pkg/enqueue/Consumption/Extension/LimitConsumptionTimeExtension.php
index f0a577930..1953aa2e6 100644
--- a/pkg/enqueue/Consumption/Extension/LimitConsumptionTimeExtension.php
+++ b/pkg/enqueue/Consumption/Extension/LimitConsumptionTimeExtension.php
@@ -17,9 +17,6 @@ class LimitConsumptionTimeExtension implements PreConsumeExtensionInterface, Pos
*/
protected $timeLimit;
- /**
- * @param \DateTime $timeLimit
- */
public function __construct(\DateTime $timeLimit)
{
$this->timeLimit = $timeLimit;
@@ -53,8 +50,8 @@ protected function shouldBeStopped(LoggerInterface $logger): bool
$logger->debug(sprintf(
'[LimitConsumptionTimeExtension] Execution interrupted as limit time has passed.'.
' now: "%s", time-limit: "%s"',
- $now->format(DATE_ISO8601),
- $this->timeLimit->format(DATE_ISO8601)
+ $now->format(\DATE_ISO8601),
+ $this->timeLimit->format(\DATE_ISO8601)
));
return true;
diff --git a/pkg/enqueue/Consumption/Extension/LogExtension.php b/pkg/enqueue/Consumption/Extension/LogExtension.php
index 14383c4d1..6338ad314 100644
--- a/pkg/enqueue/Consumption/Extension/LogExtension.php
+++ b/pkg/enqueue/Consumption/Extension/LogExtension.php
@@ -30,7 +30,7 @@ public function onMessageReceived(MessageReceived $context): void
{
$message = $context->getMessage();
- $context->getLogger()->debug("Received from {queueName}\t{body}", [
+ $context->getLogger()->debug('Received from {queueName}', [
'queueName' => $context->getConsumer()->getQueue()->getQueueName(),
'redelivered' => $message->isRedelivered(),
'body' => Stringify::that($message->getBody()),
@@ -45,12 +45,13 @@ public function onPostMessageReceived(PostMessageReceived $context): void
$queue = $context->getConsumer()->getQueue();
$result = $context->getResult();
+ $logMessage = 'Processed from {queueName}';
+
$reason = '';
- $logMessage = "Processed from {queueName}\t{body}\t{result}";
if ($result instanceof Result && $result->getReason()) {
$reason = $result->getReason();
- $logMessage .= ' {reason}';
}
+
$logContext = [
'result' => str_replace('enqueue.', '', $result),
'reason' => $reason,
diff --git a/pkg/enqueue/Consumption/Extension/LoggerExtension.php b/pkg/enqueue/Consumption/Extension/LoggerExtension.php
index 0de2739c1..90e92be8a 100644
--- a/pkg/enqueue/Consumption/Extension/LoggerExtension.php
+++ b/pkg/enqueue/Consumption/Extension/LoggerExtension.php
@@ -13,9 +13,6 @@ class LoggerExtension implements InitLoggerExtensionInterface
*/
private $logger;
- /**
- * @param LoggerInterface $logger
- */
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
@@ -28,7 +25,7 @@ public function onInitLogger(InitLogger $context): void
if ($previousLogger !== $this->logger) {
$context->changeLogger($this->logger);
- $this->logger->debug(sprintf('Change logger from "%s" to "%s"', get_class($previousLogger), get_class($this->logger)));
+ $this->logger->debug(sprintf('Change logger from "%s" to "%s"', $previousLogger::class, get_class($this->logger)));
}
}
}
diff --git a/pkg/enqueue/Consumption/Extension/NicenessExtension.php b/pkg/enqueue/Consumption/Extension/NicenessExtension.php
index 983e04b0e..436a8ec0f 100644
--- a/pkg/enqueue/Consumption/Extension/NicenessExtension.php
+++ b/pkg/enqueue/Consumption/Extension/NicenessExtension.php
@@ -20,10 +20,7 @@ class NicenessExtension implements StartExtensionInterface
public function __construct($niceness)
{
if (false === is_int($niceness)) {
- throw new \InvalidArgumentException(sprintf(
- 'Expected niceness value is int but got: "%s"',
- is_object($niceness) ? get_class($niceness) : gettype($niceness)
- ));
+ throw new \InvalidArgumentException(sprintf('Expected niceness value is int but got: "%s"', is_object($niceness) ? $niceness::class : gettype($niceness)));
}
$this->niceness = $niceness;
@@ -34,10 +31,7 @@ public function onStart(Start $context): void
if (0 !== $this->niceness) {
$changed = @proc_nice($this->niceness);
if (!$changed) {
- throw new \InvalidArgumentException(sprintf(
- 'Cannot change process niceness, got warning: "%s"',
- error_get_last()['message']
- ));
+ throw new \InvalidArgumentException(sprintf('Cannot change process niceness, got warning: "%s"', error_get_last()['message']));
}
}
}
diff --git a/pkg/enqueue/Consumption/Extension/SignalExtension.php b/pkg/enqueue/Consumption/Extension/SignalExtension.php
index 67354b99d..8ea5307d5 100644
--- a/pkg/enqueue/Consumption/Extension/SignalExtension.php
+++ b/pkg/enqueue/Consumption/Extension/SignalExtension.php
@@ -33,9 +33,9 @@ public function onStart(Start $context): void
pcntl_async_signals(true);
- pcntl_signal(SIGTERM, [$this, 'handleSignal']);
- pcntl_signal(SIGQUIT, [$this, 'handleSignal']);
- pcntl_signal(SIGINT, [$this, 'handleSignal']);
+ pcntl_signal(\SIGTERM, [$this, 'handleSignal']);
+ pcntl_signal(\SIGQUIT, [$this, 'handleSignal']);
+ pcntl_signal(\SIGINT, [$this, 'handleSignal']);
$this->logger = $context->getLogger();
$this->interruptConsumption = false;
@@ -71,9 +71,9 @@ public function handleSignal(int $signal): void
}
switch ($signal) {
- case SIGTERM: // 15 : supervisor default stop
- case SIGQUIT: // 3 : kill -s QUIT
- case SIGINT: // 2 : ctrl+c
+ case \SIGTERM: // 15 : supervisor default stop
+ case \SIGQUIT: // 3 : kill -s QUIT
+ case \SIGINT: // 2 : ctrl+c
if ($this->logger) {
$this->logger->debug('[SignalExtension] Interrupt consumption');
}
diff --git a/pkg/enqueue/Consumption/FallbackSubscriptionConsumer.php b/pkg/enqueue/Consumption/FallbackSubscriptionConsumer.php
index cdd6fb13a..15e2f273b 100644
--- a/pkg/enqueue/Consumption/FallbackSubscriptionConsumer.php
+++ b/pkg/enqueue/Consumption/FallbackSubscriptionConsumer.php
@@ -25,13 +25,13 @@ public function __construct()
$this->subscribers = [];
}
- public function consume(int $timeout = 0): void
+ public function consume(int $timeoutMs = 0): void
{
- if (empty($this->subscribers)) {
+ if (!$subscriberCount = \count($this->subscribers)) {
throw new \LogicException('No subscribers');
}
- $timeout /= 1000;
+ $timeout = $timeoutMs / 1000;
$endAt = microtime(true) + $timeout;
while (true) {
@@ -41,13 +41,13 @@ public function consume(int $timeout = 0): void
* @var callable $processor
*/
foreach ($this->subscribers as $queueName => list($consumer, $callback)) {
- $message = $consumer->receiveNoWait();
+ $message = 1 === $subscriberCount ? $consumer->receive($timeoutMs) : $consumer->receiveNoWait();
if ($message) {
if (false === call_user_func($callback, $message, $consumer)) {
return;
}
- } else {
+ } elseif (1 !== $subscriberCount) {
if ($timeout && microtime(true) >= $endAt) {
return;
}
diff --git a/pkg/enqueue/Consumption/QueueConsumer.php b/pkg/enqueue/Consumption/QueueConsumer.php
index ca858ac7d..f43f5c41b 100644
--- a/pkg/enqueue/Consumption/QueueConsumer.php
+++ b/pkg/enqueue/Consumption/QueueConsumer.php
@@ -43,7 +43,7 @@ final class QueueConsumer implements QueueConsumerInterface
private $boundProcessors;
/**
- * @var int|float in milliseconds
+ * @var int in milliseconds
*/
private $receiveTimeout;
@@ -59,14 +59,14 @@ final class QueueConsumer implements QueueConsumerInterface
/**
* @param BoundProcessor[] $boundProcessors
- * @param int|float $receiveTimeout the time in milliseconds queue consumer waits for a message (10 ms by default)
+ * @param int $receiveTimeout the time in milliseconds queue consumer waits for a message (10000 ms by default)
*/
public function __construct(
InteropContext $interopContext,
- ExtensionInterface $extension = null,
+ ?ExtensionInterface $extension = null,
array $boundProcessors = [],
- LoggerInterface $logger = null,
- int $receiveTimeout = 10000
+ ?LoggerInterface $logger = null,
+ int $receiveTimeout = 10000,
) {
$this->interopContext = $interopContext;
$this->receiveTimeout = $receiveTimeout;
@@ -122,7 +122,7 @@ public function bindCallback($queue, callable $processor): QueueConsumerInterfac
return $this->bind($queue, new CallbackProcessor($processor));
}
- public function consume(ExtensionInterface $runtimeExtension = null): void
+ public function consume(?ExtensionInterface $runtimeExtension = null): void
{
$extension = $runtimeExtension ?
new ChainExtension([$this->staticExtension, $runtimeExtension]) :
@@ -147,7 +147,7 @@ public function consume(ExtensionInterface $runtimeExtension = null): void
$extension->onStart($start);
if ($start->isExecutionInterrupted()) {
- $this->onEnd($extension, $startTime);
+ $this->onEnd($extension, $startTime, $start->getExitStatus());
return;
}
@@ -195,12 +195,12 @@ public function consume(ExtensionInterface $runtimeExtension = null): void
if (null === $result) {
try {
$result = $processor->process($message, $this->interopContext);
- } catch (\Exception $e) {
- $result = $this->onProcessorException($extension, $message, $e, $receivedAt);
+ } catch (\Exception|\Throwable $e) {
+ $result = $this->onProcessorException($extension, $consumer, $message, $e, $receivedAt);
}
}
- $messageResult = new MessageResult($this->interopContext, $message, $result, $receivedAt, $this->logger);
+ $messageResult = new MessageResult($this->interopContext, $consumer, $message, $result, $receivedAt, $this->logger);
$extension->onResult($messageResult);
$result = $messageResult->getResult();
@@ -256,7 +256,7 @@ public function consume(ExtensionInterface $runtimeExtension = null): void
$extension->onPreConsume($preConsume);
if ($preConsume->isExecutionInterrupted()) {
- $this->onEnd($extension, $startTime, $subscriptionConsumer);
+ $this->onEnd($extension, $startTime, $preConsume->getExitStatus(), $subscriptionConsumer);
return;
}
@@ -267,32 +267,29 @@ public function consume(ExtensionInterface $runtimeExtension = null): void
$extension->onPostConsume($postConsume);
if ($interruptExecution || $postConsume->isExecutionInterrupted()) {
- $this->onEnd($extension, $startTime, $subscriptionConsumer);
+ $this->onEnd($extension, $startTime, $postConsume->getExitStatus(), $subscriptionConsumer);
return;
}
++$cycle;
}
-
- $this->enableSubscriptionConsumer = $enableSubscriptionConsumer;
}
/**
* @internal
- *
- * @param SubscriptionConsumer $fallbackSubscriptionConsumer
*/
public function setFallbackSubscriptionConsumer(SubscriptionConsumer $fallbackSubscriptionConsumer): void
{
$this->fallbackSubscriptionConsumer = $fallbackSubscriptionConsumer;
}
- private function onEnd(ExtensionInterface $extension, int $startTime, SubscriptionConsumer $subscriptionConsumer = null): void
+ private function onEnd(ExtensionInterface $extension, int $startTime, ?int $exitStatus = null, ?SubscriptionConsumer $subscriptionConsumer = null): void
{
$endTime = (int) (microtime(true) * 1000);
- $extension->onEnd(new End($this->interopContext, $startTime, $endTime, $this->logger));
+ $endContext = new End($this->interopContext, $startTime, $endTime, $this->logger, $exitStatus);
+ $extension->onEnd($endContext);
if ($subscriptionConsumer) {
$subscriptionConsumer->unsubscribeAll();
@@ -300,13 +297,13 @@ private function onEnd(ExtensionInterface $extension, int $startTime, Subscripti
}
/**
- * The logic is similar to one in Symfony's ExceptionListener::.
+ * The logic is similar to one in Symfony's ExceptionListener::onKernelException().
*
* https://github.com/symfony/symfony/blob/cbe289517470eeea27162fd2d523eb29c95f775f/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php#L77
*/
- private function onProcessorException(ExtensionInterface $extension, Message $message, \Exception $exception, int $receivedAt)
+ private function onProcessorException(ExtensionInterface $extension, Consumer $consumer, Message $message, \Throwable $exception, int $receivedAt)
{
- $processorException = new ProcessorException($this->interopContext, $message, $exception, $receivedAt, $this->logger);
+ $processorException = new ProcessorException($this->interopContext, $consumer, $message, $exception, $receivedAt, $this->logger);
try {
$extension->onProcessorException($processorException);
@@ -318,20 +315,18 @@ private function onProcessorException(ExtensionInterface $extension, Message $me
return $result;
} catch (\Exception $e) {
- $wrapper = $e;
- while ($prev = $wrapper->getPrevious()) {
+ $prev = $e;
+ do {
if ($exception === $wrapper = $prev) {
throw $e;
}
- }
+ } while ($prev = $wrapper->getPrevious());
- $prev = new \ReflectionProperty('Exception', 'previous');
+ $prev = new \ReflectionProperty($wrapper instanceof \Exception ? \Exception::class : \Error::class, 'previous');
$prev->setAccessible(true);
$prev->setValue($wrapper, $exception);
throw $e;
}
-
- throw $exception;
}
}
diff --git a/pkg/enqueue/Consumption/QueueConsumerInterface.php b/pkg/enqueue/Consumption/QueueConsumerInterface.php
index c9c99ef15..ee2565252 100644
--- a/pkg/enqueue/Consumption/QueueConsumerInterface.php
+++ b/pkg/enqueue/Consumption/QueueConsumerInterface.php
@@ -27,17 +27,14 @@ public function bind($queueName, Processor $processor): self;
/**
* @param string|InteropQueue $queueName
- * @param mixed $queue
*/
- public function bindCallback($queue, callable $processor): self;
+ public function bindCallback($queueName, callable $processor): self;
/**
* Runtime extension - is an extension or a collection of extensions which could be set on runtime.
* Here's a good example: @see LimitsExtensionsCommandTrait.
*
- * @param ExtensionInterface|null $runtimeExtension
- *
* @throws \Exception
*/
- public function consume(ExtensionInterface $runtimeExtension = null): void;
+ public function consume(?ExtensionInterface $runtimeExtension = null): void;
}
diff --git a/pkg/enqueue/Consumption/Result.php b/pkg/enqueue/Consumption/Result.php
index b94b7447c..69dd7907b 100644
--- a/pkg/enqueue/Consumption/Result.php
+++ b/pkg/enqueue/Consumption/Result.php
@@ -10,19 +10,19 @@ class Result
/**
* @see Processor::ACK for more details
*/
- const ACK = Processor::ACK;
+ public const ACK = Processor::ACK;
/**
- * @see Processor::ACK for more details
+ * @see Processor::REJECT for more details
*/
- const REJECT = Processor::REJECT;
+ public const REJECT = Processor::REJECT;
/**
- * @see Processor::ACK for more details
+ * @see Processor::REQUEUE for more details
*/
- const REQUEUE = Processor::REQUEUE;
+ public const REQUEUE = Processor::REQUEUE;
- const ALREADY_ACKNOWLEDGED = 'enqueue.already_acknowledged';
+ public const ALREADY_ACKNOWLEDGED = 'enqueue.already_acknowledged';
/**
* @var string
@@ -39,10 +39,6 @@ class Result
*/
private $reply;
- /**
- * @param mixed $status
- * @param mixed $reason
- */
public function __construct($status, $reason = '')
{
$this->status = (string) $status;
@@ -81,10 +77,7 @@ public function getReply()
return $this->reply;
}
- /**
- * @param InteropMessage|null $reply
- */
- public function setReply(InteropMessage $reply = null)
+ public function setReply(?InteropMessage $reply = null)
{
$this->reply = $reply;
}
@@ -96,7 +89,7 @@ public function setReply(InteropMessage $reply = null)
*/
public static function ack($reason = '')
{
- return new static(self::ACK, $reason);
+ return new self(self::ACK, $reason);
}
/**
@@ -106,7 +99,7 @@ public static function ack($reason = '')
*/
public static function reject($reason)
{
- return new static(self::REJECT, $reason);
+ return new self(self::REJECT, $reason);
}
/**
@@ -116,13 +109,12 @@ public static function reject($reason)
*/
public static function requeue($reason = '')
{
- return new static(self::REQUEUE, $reason);
+ return new self(self::REQUEUE, $reason);
}
/**
- * @param InteropMessage $replyMessage
- * @param string $status
- * @param string|null $reason
+ * @param string $status
+ * @param string|null $reason
*
* @return static
*/
@@ -130,7 +122,7 @@ public static function reply(InteropMessage $replyMessage, $status = self::ACK,
{
$status = null === $status ? self::ACK : $status;
- $result = new static($status, $reason);
+ $result = new self($status, $reason);
$result->setReply($replyMessage);
return $result;
diff --git a/pkg/enqueue/Container/Container.php b/pkg/enqueue/Container/Container.php
index 255def33b..5abec276c 100644
--- a/pkg/enqueue/Container/Container.php
+++ b/pkg/enqueue/Container/Container.php
@@ -25,7 +25,7 @@ public function get($id)
return $this->services[$id];
}
- public function has($id)
+ public function has(string $id): bool
{
return array_key_exists($id, $this->services);
}
diff --git a/pkg/enqueue/Doctrine/DoctrineConnectionFactoryFactory.php b/pkg/enqueue/Doctrine/DoctrineConnectionFactoryFactory.php
new file mode 100644
index 000000000..1fd336c4e
--- /dev/null
+++ b/pkg/enqueue/Doctrine/DoctrineConnectionFactoryFactory.php
@@ -0,0 +1,54 @@
+doctrine = $doctrine;
+ $this->fallbackFactory = $fallbackFactory;
+ }
+
+ public function create($config): ConnectionFactory
+ {
+ if (is_string($config)) {
+ $config = ['dsn' => $config];
+ }
+
+ if (false == is_array($config)) {
+ throw new \InvalidArgumentException('The config must be either array or DSN string.');
+ }
+
+ if (false == array_key_exists('dsn', $config)) {
+ throw new \InvalidArgumentException('The config must have dsn key set.');
+ }
+
+ $dsn = Dsn::parseFirst($config['dsn']);
+
+ if ('doctrine' === $dsn->getScheme()) {
+ $config = $dsn->getQuery();
+ $config['connection_name'] = $dsn->getHost();
+
+ return new ManagerRegistryConnectionFactory($this->doctrine, $config);
+ }
+
+ return $this->fallbackFactory->create($config);
+ }
+}
diff --git a/pkg/enqueue/Doctrine/DoctrineDriverFactory.php b/pkg/enqueue/Doctrine/DoctrineDriverFactory.php
new file mode 100644
index 000000000..aab6489aa
--- /dev/null
+++ b/pkg/enqueue/Doctrine/DoctrineDriverFactory.php
@@ -0,0 +1,41 @@
+fallbackFactory = $fallbackFactory;
+ }
+
+ public function create(ConnectionFactory $factory, Config $config, RouteCollection $collection): DriverInterface
+ {
+ $dsn = $config->getTransportOption('dsn');
+
+ if (empty($dsn)) {
+ throw new \LogicException('This driver factory relies on dsn option from transport config. The option is empty or not set.');
+ }
+
+ $dsn = Dsn::parseFirst($dsn);
+
+ if ('doctrine' === $dsn->getScheme()) {
+ return new DbalDriver($factory->createContext(), $config, $collection);
+ }
+
+ return $this->fallbackFactory->create($factory, $config, $collection);
+ }
+}
diff --git a/pkg/enqueue/Doctrine/DoctrineSchemaCompilerPass.php b/pkg/enqueue/Doctrine/DoctrineSchemaCompilerPass.php
new file mode 100644
index 000000000..0eb378470
--- /dev/null
+++ b/pkg/enqueue/Doctrine/DoctrineSchemaCompilerPass.php
@@ -0,0 +1,39 @@
+hasDefinition('doctrine')) {
+ return;
+ }
+
+ foreach ($container->getParameter('enqueue.transports') as $name) {
+ $diUtils = DiUtils::create(TransportFactory::MODULE, $name);
+
+ $container->register($diUtils->format('connection_factory_factory.outer'), DoctrineConnectionFactoryFactory::class)
+ ->setDecoratedService($diUtils->format('connection_factory_factory'), $diUtils->format('connection_factory_factory.inner'))
+ ->addArgument(new Reference('doctrine'))
+ ->addArgument(new Reference($diUtils->format('connection_factory_factory.inner')))
+ ;
+ }
+
+ foreach ($container->getParameter('enqueue.clients') as $name) {
+ $diUtils = DiUtils::create(ClientFactory::MODULE, $name);
+
+ $container->register($diUtils->format('driver_factory.outer'), DoctrineDriverFactory::class)
+ ->setDecoratedService($diUtils->format('driver_factory'), $diUtils->format('driver_factory.inner'))
+ ->addArgument(new Reference($diUtils->format('driver_factory.inner')))
+ ;
+ }
+ }
+}
diff --git a/pkg/enqueue/README.md b/pkg/enqueue/README.md
index b8cb04cb9..947a9e255 100644
--- a/pkg/enqueue/README.md
+++ b/pkg/enqueue/README.md
@@ -1,29 +1,42 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Message Queue.
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/enqueue)
+[](https://github.com/php-enqueue/enqueue/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/enqueue)
[](https://packagist.org/packages/enqueue/enqueue)
-
-It contains advanced features build on top of a transport component.
+
+It contains advanced features build on top of a transport component.
Client component kind of plug and play things or consumption component that simplify message processing a lot.
-Read more about it in documentation.
+Read more about it in documentation.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
-It is released under the [MIT License](LICENSE).
\ No newline at end of file
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/enqueue/Resources.php b/pkg/enqueue/Resources.php
index 21172c636..4c500006f 100644
--- a/pkg/enqueue/Resources.php
+++ b/pkg/enqueue/Resources.php
@@ -14,8 +14,11 @@
use Enqueue\Pheanstalk\PheanstalkConnectionFactory;
use Enqueue\RdKafka\RdKafkaConnectionFactory;
use Enqueue\Redis\RedisConnectionFactory;
+use Enqueue\Sns\SnsConnectionFactory;
+use Enqueue\SnsQs\SnsQsConnectionFactory;
use Enqueue\Sqs\SqsConnectionFactory;
use Enqueue\Stomp\StompConnectionFactory;
+use Enqueue\Wamp\WampConnectionFactory;
use Interop\Queue\ConnectionFactory;
final class Resources
@@ -28,7 +31,7 @@ final class Resources
*
* @var array
*/
- private static $knownConnections = null;
+ private static $knownConnections;
private function __construct()
{
@@ -40,7 +43,7 @@ public static function getAvailableConnections(): array
$availableMap = [];
foreach ($map as $connectionClass => $item) {
- if (class_exists($connectionClass)) {
+ if (\class_exists($connectionClass)) {
$availableMap[$connectionClass] = $item;
}
}
@@ -142,7 +145,7 @@ public static function getKnownConnections(): array
'package' => 'enqueue/rdkafka',
];
$map[RedisConnectionFactory::class] = [
- 'schemes' => ['redis'],
+ 'schemes' => ['redis', 'rediss'],
'supportedSchemeExtensions' => ['predis', 'phpredis'],
'package' => 'enqueue/redis',
];
@@ -154,6 +157,14 @@ public static function getKnownConnections(): array
'schemes' => ['sqs'],
'supportedSchemeExtensions' => [],
'package' => 'enqueue/sqs', ];
+ $map[SnsConnectionFactory::class] = [
+ 'schemes' => ['sns'],
+ 'supportedSchemeExtensions' => [],
+ 'package' => 'enqueue/sns', ];
+ $map[SnsQsConnectionFactory::class] = [
+ 'schemes' => ['snsqs'],
+ 'supportedSchemeExtensions' => [],
+ 'package' => 'enqueue/snsqs', ];
$map[GpsConnectionFactory::class] = [
'schemes' => ['gps'],
'supportedSchemeExtensions' => [],
@@ -163,6 +174,11 @@ public static function getKnownConnections(): array
'supportedSchemeExtensions' => [],
'package' => 'enqueue/mongodb',
];
+ $map[WampConnectionFactory::class] = [
+ 'schemes' => ['wamp', 'ws'],
+ 'supportedSchemeExtensions' => [],
+ 'package' => 'enqueue/wamp',
+ ];
self::$knownConnections = $map;
}
@@ -172,9 +188,9 @@ public static function getKnownConnections(): array
public static function addConnection(string $connectionFactoryClass, array $schemes, array $extensions, string $package): void
{
- if (class_exists($connectionFactoryClass)) {
+ if (\class_exists($connectionFactoryClass)) {
if (false == (new \ReflectionClass($connectionFactoryClass))->implementsInterface(ConnectionFactory::class)) {
- throw new \InvalidArgumentException(sprintf('The connection factory class "%s" must implement "%s" interface.', $connectionFactoryClass, ConnectionFactory::class));
+ throw new \InvalidArgumentException(\sprintf('The connection factory class "%s" must implement "%s" interface.', $connectionFactoryClass, ConnectionFactory::class));
}
}
diff --git a/pkg/enqueue/Router/Recipient.php b/pkg/enqueue/Router/Recipient.php
index c7eac6af6..d2f668f42 100644
--- a/pkg/enqueue/Router/Recipient.php
+++ b/pkg/enqueue/Router/Recipient.php
@@ -17,10 +17,6 @@ class Recipient
*/
private $message;
- /**
- * @param Destination $destination
- * @param InteropMessage $message
- */
public function __construct(Destination $destination, InteropMessage $message)
{
$this->destination = $destination;
diff --git a/pkg/enqueue/Router/RecipientListRouterInterface.php b/pkg/enqueue/Router/RecipientListRouterInterface.php
index d00dd2abb..6bb950fdc 100644
--- a/pkg/enqueue/Router/RecipientListRouterInterface.php
+++ b/pkg/enqueue/Router/RecipientListRouterInterface.php
@@ -7,8 +7,6 @@
interface RecipientListRouterInterface
{
/**
- * @param InteropMessage $message
- *
* @return \Traversable|Recipient[]
*/
public function route(InteropMessage $message);
diff --git a/pkg/enqueue/Router/RouteRecipientListProcessor.php b/pkg/enqueue/Router/RouteRecipientListProcessor.php
index 22e32e2ca..22488e33f 100644
--- a/pkg/enqueue/Router/RouteRecipientListProcessor.php
+++ b/pkg/enqueue/Router/RouteRecipientListProcessor.php
@@ -13,17 +13,11 @@ class RouteRecipientListProcessor implements Processor
*/
private $router;
- /**
- * @param RecipientListRouterInterface $router
- */
public function __construct(RecipientListRouterInterface $router)
{
$this->router = $router;
}
- /**
- * {@inheritdoc}
- */
public function process(InteropMessage $message, Context $context)
{
$producer = $context->createProducer();
diff --git a/pkg/enqueue/Rpc/Promise.php b/pkg/enqueue/Rpc/Promise.php
index 0a5d28f0c..01b47e1f6 100644
--- a/pkg/enqueue/Rpc/Promise.php
+++ b/pkg/enqueue/Rpc/Promise.php
@@ -31,11 +31,6 @@ class Promise
*/
private $message;
- /**
- * @param \Closure $receiveCallback
- * @param \Closure $receiveNoWaitCallback
- * @param \Closure $finallyCallback
- */
public function __construct(\Closure $receiveCallback, \Closure $receiveNoWaitCallback, \Closure $finallyCallback)
{
$this->receiveCallback = $receiveCallback;
@@ -106,8 +101,7 @@ public function isDeleteReplyQueue()
}
/**
- * @param \Closure $cb
- * @param array $args
+ * @param array $args
*
* @return InteropMessage
*/
@@ -116,8 +110,7 @@ private function doReceive(\Closure $cb, ...$args)
$message = call_user_func_array($cb, $args);
if (null !== $message && false == $message instanceof InteropMessage) {
- throw new \RuntimeException(sprintf(
- 'Expected "%s" but got: "%s"', InteropMessage::class, is_object($message) ? get_class($message) : gettype($message)));
+ throw new \RuntimeException(sprintf('Expected "%s" but got: "%s"', InteropMessage::class, is_object($message) ? $message::class : gettype($message)));
}
return $message;
diff --git a/pkg/enqueue/Rpc/RpcClient.php b/pkg/enqueue/Rpc/RpcClient.php
index 591a4cc19..bd3d7cedb 100644
--- a/pkg/enqueue/Rpc/RpcClient.php
+++ b/pkg/enqueue/Rpc/RpcClient.php
@@ -19,20 +19,14 @@ class RpcClient
*/
private $rpcFactory;
- /**
- * @param Context $context
- * @param RpcFactory $promiseFactory
- */
- public function __construct(Context $context, RpcFactory $promiseFactory = null)
+ public function __construct(Context $context, ?RpcFactory $promiseFactory = null)
{
$this->context = $context;
$this->rpcFactory = $promiseFactory ?: new RpcFactory($context);
}
/**
- * @param Destination $destination
- * @param InteropMessage $message
- * @param int $timeout
+ * @param int $timeout
*
* @throws TimeoutException if the wait timeout is reached
*
@@ -44,9 +38,7 @@ public function call(Destination $destination, InteropMessage $message, $timeout
}
/**
- * @param Destination $destination
- * @param InteropMessage $message
- * @param int $timeout
+ * @param int $timeout
*
* @return Promise
*/
diff --git a/pkg/enqueue/Rpc/RpcFactory.php b/pkg/enqueue/Rpc/RpcFactory.php
index bd054b186..9100babd3 100644
--- a/pkg/enqueue/Rpc/RpcFactory.php
+++ b/pkg/enqueue/Rpc/RpcFactory.php
@@ -11,9 +11,6 @@ class RpcFactory
*/
private $context;
- /**
- * @param Context $context
- */
public function __construct(Context $context)
{
$this->context = $context;
diff --git a/pkg/enqueue/Rpc/TimeoutException.php b/pkg/enqueue/Rpc/TimeoutException.php
index a0b065511..a7f68b967 100644
--- a/pkg/enqueue/Rpc/TimeoutException.php
+++ b/pkg/enqueue/Rpc/TimeoutException.php
@@ -12,6 +12,6 @@ class TimeoutException extends \LogicException
*/
public static function create($timeout, $correlationId)
{
- return new static(sprintf('Rpc call timeout is reached without receiving a reply message. Timeout: %s, CorrelationId: %s', $timeout, $correlationId));
+ return new self(sprintf('Rpc call timeout is reached without receiving a reply message. Timeout: %s, CorrelationId: %s', $timeout, $correlationId));
}
}
diff --git a/pkg/enqueue/Symfony/Client/ConsumeCommand.php b/pkg/enqueue/Symfony/Client/ConsumeCommand.php
index d8b4efbba..94b56ad10 100644
--- a/pkg/enqueue/Symfony/Client/ConsumeCommand.php
+++ b/pkg/enqueue/Symfony/Client/ConsumeCommand.php
@@ -4,7 +4,7 @@
use Enqueue\Client\DriverInterface;
use Enqueue\Consumption\ChainExtension;
-use Enqueue\Consumption\Extension\LoggerExtension;
+use Enqueue\Consumption\Extension\ExitStatusExtension;
use Enqueue\Consumption\ExtensionInterface;
use Enqueue\Consumption\QueueConsumerInterface;
use Enqueue\Symfony\Consumption\ChooseLoggerCommandTrait;
@@ -13,27 +13,31 @@
use Interop\Queue\Processor;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
+#[AsCommand('enqueue:consume')]
class ConsumeCommand extends Command
{
+ use ChooseLoggerCommandTrait;
use LimitsExtensionsCommandTrait;
- use SetupBrokerExtensionCommandTrait;
use QueueConsumerOptionsCommandTrait;
- use ChooseLoggerCommandTrait;
-
- protected static $defaultName = 'enqueue:consume';
+ use SetupBrokerExtensionCommandTrait;
/**
* @var ContainerInterface
*/
private $container;
+ /**
+ * @var string
+ */
+ private $defaultClient;
+
/**
* @var string
*/
@@ -51,16 +55,18 @@ class ConsumeCommand extends Command
public function __construct(
ContainerInterface $container,
+ string $defaultClient,
string $queueConsumerIdPattern = 'enqueue.client.%s.queue_consumer',
string $driverIdPattern = 'enqueue.client.%s.driver',
- string $processorIdPatter = 'enqueue.client.%s.delegate_processor'
+ string $processorIdPatter = 'enqueue.client.%s.delegate_processor',
) {
- parent::__construct(self::$defaultName);
-
$this->container = $container;
+ $this->defaultClient = $defaultClient;
$this->queueConsumerIdPattern = $queueConsumerIdPattern;
$this->driverIdPattern = $driverIdPattern;
$this->processorIdPattern = $processorIdPatter;
+
+ parent::__construct();
}
protected function configure(): void
@@ -77,18 +83,18 @@ protected function configure(): void
'It select an appropriate message processor based on a message headers')
->addArgument('client-queue-names', InputArgument::IS_ARRAY, 'Queues to consume messages from')
->addOption('skip', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, 'Queues to skip consumption of messages from', [])
- ->addOption('client', 'c', InputOption::VALUE_OPTIONAL, 'The client to consume messages from.', 'default')
+ ->addOption('client', 'c', InputOption::VALUE_OPTIONAL, 'The client to consume messages from.', $this->defaultClient)
;
}
- protected function execute(InputInterface $input, OutputInterface $output): ?int
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
$client = $input->getOption('client');
try {
$consumer = $this->getQueueConsumer($client);
} catch (NotFoundExceptionInterface $e) {
- throw new \LogicException(sprintf('Client "%s" is not supported.', $client), null, $e);
+ throw new \LogicException(sprintf('Client "%s" is not supported.', $client), previous: $e);
}
$driver = $this->getDriver($client);
@@ -96,37 +102,53 @@ protected function execute(InputInterface $input, OutputInterface $output): ?int
$this->setQueueConsumerOptions($consumer, $input);
- $clientQueueNames = $input->getArgument('client-queue-names');
- if (empty($clientQueueNames)) {
- $clientQueueNames[$driver->getConfig()->getDefaultQueue()] = true;
- $clientQueueNames[$driver->getConfig()->getRouterQueue()] = true;
+ $allQueues[$driver->getConfig()->getDefaultQueue()] = true;
+ $allQueues[$driver->getConfig()->getRouterQueue()] = true;
+ foreach ($driver->getRouteCollection()->all() as $route) {
+ if (false == $route->getQueue()) {
+ continue;
+ }
+ if ($route->isProcessorExternal()) {
+ continue;
+ }
- foreach ($driver->getRouteCollection()->all() as $route) {
- if ($route->getQueue()) {
- $clientQueueNames[$route->getQueue()] = true;
+ $allQueues[$route->getQueue()] = $route->isPrefixQueue();
+ }
+
+ $selectedQueues = $input->getArgument('client-queue-names');
+ if (empty($selectedQueues)) {
+ $queues = $allQueues;
+ } else {
+ $queues = [];
+ foreach ($selectedQueues as $queue) {
+ if (false == array_key_exists($queue, $allQueues)) {
+ throw new \LogicException(sprintf('There is no such queue "%s". Available are "%s"', $queue, implode('", "', array_keys($allQueues))));
}
- }
- foreach ($input->getOption('skip') as $skipClientQueueName) {
- unset($clientQueueNames[$skipClientQueueName]);
+ $queues[$queue] = $allQueues[$queue];
}
+ }
- $clientQueueNames = array_keys($clientQueueNames);
+ foreach ($input->getOption('skip') as $skipQueue) {
+ unset($queues[$skipQueue]);
}
- foreach ($clientQueueNames as $clientQueueName) {
- $queue = $driver->createQueue($clientQueueName);
+ foreach ($queues as $queue => $prefix) {
+ $queue = $driver->createQueue($queue, $prefix);
$consumer->bind($queue, $processor);
}
- $consumer->consume($this->getRuntimeExtensions($input, $output));
+ $runtimeExtensionChain = $this->getRuntimeExtensions($input, $output);
+ $exitStatusExtension = new ExitStatusExtension();
+
+ $consumer->consume(new ChainExtension([$runtimeExtensionChain, $exitStatusExtension]));
- return null;
+ return $exitStatusExtension->getExitStatus() ?? 0;
}
protected function getRuntimeExtensions(InputInterface $input, OutputInterface $output): ExtensionInterface
{
- $extensions = [new LoggerExtension(new ConsoleLogger($output))];
+ $extensions = [];
$extensions = array_merge($extensions, $this->getLimitsExtensions($input, $output));
$driver = $this->getDriver($input->getOption('client'));
diff --git a/pkg/enqueue/Symfony/Client/DependencyInjection/AnalyzeRouteCollectionPass.php b/pkg/enqueue/Symfony/Client/DependencyInjection/AnalyzeRouteCollectionPass.php
index c8b140cfd..577f15902 100644
--- a/pkg/enqueue/Symfony/Client/DependencyInjection/AnalyzeRouteCollectionPass.php
+++ b/pkg/enqueue/Symfony/Client/DependencyInjection/AnalyzeRouteCollectionPass.php
@@ -3,52 +3,47 @@
namespace Enqueue\Symfony\Client\DependencyInjection;
use Enqueue\Client\RouteCollection;
+use Enqueue\Symfony\DiUtils;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
final class AnalyzeRouteCollectionPass implements CompilerPassInterface
{
- /**
- * @var string
- */
- private $name;
-
- public function __construct(string $clientName)
+ public function process(ContainerBuilder $container): void
{
- if (empty($clientName)) {
- throw new \InvalidArgumentException('The name could not be empty.');
+ if (false == $container->hasParameter('enqueue.clients')) {
+ throw new \LogicException('The "enqueue.clients" parameter must be set.');
}
- $this->name = $clientName;
- }
+ $names = $container->getParameter('enqueue.clients');
- public function process(ContainerBuilder $container): void
- {
- $routeCollectionId = sprintf('enqueue.client.%s.route_collection', $this->name);
- if (false == $container->hasDefinition($routeCollectionId)) {
- return;
- }
+ foreach ($names as $name) {
+ $diUtils = DiUtils::create(ClientFactory::MODULE, $name);
+
+ $routeCollectionId = $diUtils->format('route_collection');
+ if (false == $container->hasDefinition($routeCollectionId)) {
+ throw new \LogicException(sprintf('Service "%s" not found', $routeCollectionId));
+ }
- $collection = RouteCollection::fromArray($container->getDefinition($routeCollectionId)->getArgument(0));
+ $collection = RouteCollection::fromArray($container->getDefinition($routeCollectionId)->getArgument(0));
- $this->exclusiveCommandsCouldNotBeRunOnDefaultQueue($collection);
- $this->exclusiveCommandProcessorMustBeSingleOnGivenQueue($collection);
+ $this->exclusiveCommandsCouldNotBeRunOnDefaultQueue($collection);
+ $this->exclusiveCommandProcessorMustBeSingleOnGivenQueue($collection);
+ $this->customQueueNamesUnique($collection);
+ $this->defaultQueueMustBePrefixed($collection);
+ }
}
- private function exclusiveCommandsCouldNotBeRunOnDefaultQueue(RouteCollection $collection)
+ private function exclusiveCommandsCouldNotBeRunOnDefaultQueue(RouteCollection $collection): void
{
foreach ($collection->all() as $route) {
if ($route->isCommand() && $route->isProcessorExclusive() && false == $route->getQueue()) {
- throw new \LogicException(sprintf(
- 'The command "%s" processor "%s" is exclusive but queue is not specified. Exclusive processors could not be run on a default queue.',
- $route->getSource(),
- $route->getProcessor()
- ));
+ throw new \LogicException(sprintf('The command "%s" processor "%s" is exclusive but queue is not specified. Exclusive processors could not be run on a default queue.', $route->getSource(), $route->getProcessor()));
}
}
}
- private function exclusiveCommandProcessorMustBeSingleOnGivenQueue(RouteCollection $collection)
+ private function exclusiveCommandProcessorMustBeSingleOnGivenQueue(RouteCollection $collection): void
{
$prefixedQueues = [];
$queues = [];
@@ -62,29 +57,51 @@ private function exclusiveCommandProcessorMustBeSingleOnGivenQueue(RouteCollecti
if ($route->isPrefixQueue()) {
if (array_key_exists($route->getQueue(), $prefixedQueues)) {
- throw new \LogicException(sprintf(
- 'The command "%s" processor "%s" is exclusive. The queue "%s" already has another exclusive command processor "%s" bound to it.',
- $route->getSource(),
- $route->getProcessor(),
- $route->getQueue(),
- $prefixedQueues[$route->getQueue()]
- ));
+ throw new \LogicException(sprintf('The command "%s" processor "%s" is exclusive. The queue "%s" already has another exclusive command processor "%s" bound to it.', $route->getSource(), $route->getProcessor(), $route->getQueue(), $prefixedQueues[$route->getQueue()]));
}
$prefixedQueues[$route->getQueue()] = $route->getProcessor();
} else {
if (array_key_exists($route->getQueue(), $queues)) {
- throw new \LogicException(sprintf(
- 'The command "%s" processor "%s" is exclusive. The queue "%s" already has another exclusive command processor "%s" bound to it.',
- $route->getSource(),
- $route->getProcessor(),
- $route->getQueue(),
- $queues[$route->getQueue()]
- ));
+ throw new \LogicException(sprintf('The command "%s" processor "%s" is exclusive. The queue "%s" already has another exclusive command processor "%s" bound to it.', $route->getSource(), $route->getProcessor(), $route->getQueue(), $queues[$route->getQueue()]));
}
$queues[$route->getQueue()] = $route->getProcessor();
}
}
}
+
+ private function defaultQueueMustBePrefixed(RouteCollection $collection): void
+ {
+ foreach ($collection->all() as $route) {
+ if (false == $route->getQueue() && false == $route->isPrefixQueue()) {
+ throw new \LogicException('The default queue must be prefixed.');
+ }
+ }
+ }
+
+ private function customQueueNamesUnique(RouteCollection $collection): void
+ {
+ $prefixedQueues = [];
+ $notPrefixedQueues = [];
+
+ foreach ($collection->all() as $route) {
+ // default queue
+ $queueName = $route->getQueue();
+ if (false == $queueName) {
+ return;
+ }
+
+ $route->isPrefixQueue() ?
+ $prefixedQueues[$queueName] = $queueName :
+ $notPrefixedQueues[$queueName] = $queueName
+ ;
+ }
+
+ foreach ($notPrefixedQueues as $queueName) {
+ if (array_key_exists($queueName, $prefixedQueues)) {
+ throw new \LogicException(sprintf('There are prefixed and not prefixed queue with the same name "%s". This is not allowed.', $queueName));
+ }
+ }
+ }
}
diff --git a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildClientExtensionsPass.php b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildClientExtensionsPass.php
index 5cb516db1..92124f243 100644
--- a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildClientExtensionsPass.php
+++ b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildClientExtensionsPass.php
@@ -2,64 +2,62 @@
namespace Enqueue\Symfony\Client\DependencyInjection;
+use Enqueue\Symfony\DiUtils;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
final class BuildClientExtensionsPass implements CompilerPassInterface
{
- /**
- * @var string
- */
- private $name;
-
- public function __construct(string $clientName)
+ public function process(ContainerBuilder $container): void
{
- if (empty($clientName)) {
- throw new \InvalidArgumentException('The name could not be empty.');
+ if (false == $container->hasParameter('enqueue.clients')) {
+ throw new \LogicException('The "enqueue.clients" parameter must be set.');
}
- $this->name = $clientName;
- }
+ $names = $container->getParameter('enqueue.clients');
+ $defaultName = $container->getParameter('enqueue.default_client');
- public function process(ContainerBuilder $container): void
- {
- $extensionsId = sprintf('enqueue.client.%s.client_extensions', $this->name);
- if (false == $container->hasDefinition($extensionsId)) {
- return;
- }
+ foreach ($names as $name) {
+ $diUtils = DiUtils::create(ClientFactory::MODULE, $name);
+
+ $extensionsId = $diUtils->format('client_extensions');
+ if (false == $container->hasDefinition($extensionsId)) {
+ throw new \LogicException(sprintf('Service "%s" not found', $extensionsId));
+ }
- $tags = array_merge(
- $container->findTaggedServiceIds('enqueue.client_extension'),
- $container->findTaggedServiceIds('enqueue.client.extension') // TODO BC
- );
+ $tags = array_merge(
+ $container->findTaggedServiceIds('enqueue.client_extension'),
+ $container->findTaggedServiceIds('enqueue.client.extension') // TODO BC
+ );
- $groupByPriority = [];
- foreach ($tags as $serviceId => $tagAttributes) {
- foreach ($tagAttributes as $tagAttribute) {
- $client = $tagAttribute['client'] ?? 'default';
+ $groupByPriority = [];
+ foreach ($tags as $serviceId => $tagAttributes) {
+ foreach ($tagAttributes as $tagAttribute) {
+ $client = $tagAttribute['client'] ?? $defaultName;
- if ($client !== $this->name && 'all' !== $client) {
- continue;
- }
+ if ($client !== $name && 'all' !== $client) {
+ continue;
+ }
- $priority = (int) ($tagAttribute['priority'] ?? 0);
+ $priority = (int) ($tagAttribute['priority'] ?? 0);
- $groupByPriority[$priority][] = new Reference($serviceId);
+ $groupByPriority[$priority][] = new Reference($serviceId);
+ }
}
- }
- krsort($groupByPriority, SORT_NUMERIC);
+ krsort($groupByPriority, \SORT_NUMERIC);
- $flatExtensions = [];
- foreach ($groupByPriority as $extension) {
- $flatExtensions = array_merge($flatExtensions, $extension);
- }
+ $flatExtensions = [];
+ foreach ($groupByPriority as $extension) {
+ $flatExtensions = array_merge($flatExtensions, $extension);
+ }
- $extensionsService = $container->getDefinition($extensionsId);
- $extensionsService->replaceArgument(0, array_merge(
- $extensionsService->getArgument(0),
- $flatExtensions
- ));
+ $extensionsService = $container->getDefinition($extensionsId);
+ $extensionsService->replaceArgument(0, array_merge(
+ $extensionsService->getArgument(0),
+ $flatExtensions
+ ));
+ }
}
}
diff --git a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildCommandSubscriberRoutesPass.php b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildCommandSubscriberRoutesPass.php
index 3e8791a47..4adc09e9d 100644
--- a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildCommandSubscriberRoutesPass.php
+++ b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildCommandSubscriberRoutesPass.php
@@ -5,103 +5,131 @@
use Enqueue\Client\CommandSubscriberInterface;
use Enqueue\Client\Route;
use Enqueue\Client\RouteCollection;
+use Enqueue\Symfony\DiUtils;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
final class BuildCommandSubscriberRoutesPass implements CompilerPassInterface
{
- /**
- * @var string
- */
- private $name;
-
- public function __construct(string $clientName)
- {
- if (empty($clientName)) {
- throw new \InvalidArgumentException('The name could not be empty.');
- }
-
- $this->name = $clientName;
- }
-
public function process(ContainerBuilder $container): void
{
- $routeCollectionId = sprintf('enqueue.client.%s.route_collection', $this->name);
- if (false == $container->hasDefinition($routeCollectionId)) {
- return;
+ if (false == $container->hasParameter('enqueue.clients')) {
+ throw new \LogicException('The "enqueue.clients" parameter must be set.');
}
- $tag = 'enqueue.command_subscriber';
- $routeCollection = new RouteCollection([]);
- foreach ($container->findTaggedServiceIds($tag) as $serviceId => $tagAttributes) {
- $processorDefinition = $container->getDefinition($serviceId);
- if ($processorDefinition->getFactory()) {
- throw new \LogicException('The command subscriber tag could not be applied to a service created by factory.');
- }
+ $names = $container->getParameter('enqueue.clients');
+ $defaultName = $container->getParameter('enqueue.default_client');
- $processorClass = $processorDefinition->getClass();
- if (false == class_exists($processorClass)) {
- throw new \LogicException(sprintf('The processor class "%s" could not be found.', $processorClass));
+ foreach ($names as $name) {
+ $diUtils = DiUtils::create(ClientFactory::MODULE, $name);
+ $routeCollectionId = $diUtils->format('route_collection');
+ if (false == $container->hasDefinition($routeCollectionId)) {
+ throw new \LogicException(sprintf('Service "%s" not found', $routeCollectionId));
}
- if (false == is_subclass_of($processorClass, CommandSubscriberInterface::class)) {
- throw new \LogicException(sprintf('The processor must implement "%s" interface to be used with the tag "%s"', CommandSubscriberInterface::class, $tag));
- }
+ $tag = 'enqueue.command_subscriber';
+ $routeCollection = new RouteCollection([]);
+ foreach ($container->findTaggedServiceIds($tag) as $serviceId => $tagAttributes) {
+ $processorDefinition = $container->getDefinition($serviceId);
+ if ($processorDefinition->getFactory()) {
+ throw new \LogicException('The command subscriber tag could not be applied to a service created by factory.');
+ }
- foreach ($tagAttributes as $tagAttribute) {
- $client = $tagAttribute['client'] ?? 'default';
+ $processorClass = $processorDefinition->getClass() ?? $serviceId;
+ if (false == class_exists($processorClass)) {
+ throw new \LogicException(sprintf('The processor class "%s" could not be found.', $processorClass));
+ }
- if ($client !== $this->name && 'all' !== $client) {
- continue;
+ if (false == is_subclass_of($processorClass, CommandSubscriberInterface::class)) {
+ throw new \LogicException(sprintf('The processor must implement "%s" interface to be used with the tag "%s"', CommandSubscriberInterface::class, $tag));
}
- /** @var CommandSubscriberInterface $processorClass */
- $commands = $processorClass::getSubscribedCommand();
+ foreach ($tagAttributes as $tagAttribute) {
+ $client = $tagAttribute['client'] ?? $defaultName;
- if (empty($commands)) {
- throw new \LogicException('Command subscriber must return something.');
- }
+ if ($client !== $name && 'all' !== $client) {
+ continue;
+ }
- if (is_string($commands)) {
- $commands = [$commands];
- }
+ /** @var CommandSubscriberInterface $processorClass */
+ $commands = $processorClass::getSubscribedCommand();
- if (!is_array($commands)) {
- throw new \LogicException('Command subscriber configuration is invalid. Should be an array or string.');
- }
+ if (empty($commands)) {
+ throw new \LogicException('Command subscriber must return something.');
+ }
- if (isset($commands['command'])) {
- $commands = [$commands];
- }
+ if (is_string($commands)) {
+ $commands = [$commands];
+ }
+
+ if (!is_array($commands)) {
+ throw new \LogicException('Command subscriber configuration is invalid. Should be an array or string.');
+ }
+
+ // 0.8 command subscriber
+ if (isset($commands['processorName'])) {
+ @trigger_error('The command subscriber 0.8 syntax is deprecated since Enqueue 0.9.', \E_USER_DEPRECATED);
+
+ $source = $commands['processorName'];
+ $processor = $params['processorName'] ?? $serviceId;
+
+ $options = $commands;
+ unset(
+ $options['processorName'],
+ $options['queueName'],
+ $options['queueNameHardcoded'],
+ $options['exclusive'],
+ $options['topic'],
+ $options['source'],
+ $options['source_type'],
+ $options['processor'],
+ $options['options']
+ );
- foreach ($commands as $key => $params) {
- if (is_string($params)) {
- $routeCollection->add(new Route($params, Route::COMMAND, $serviceId, ['processor_service_id' => $serviceId]));
- } elseif (is_array($params)) {
- $source = $params['command'] ?? null;
- $processor = $params['processor'] ?? $serviceId;
- unset($params['command'], $params['source'], $params['source_type'], $params['processor'], $params['options']);
- $options = $params;
$options['processor_service_id'] = $serviceId;
+ if (isset($commands['queueName'])) {
+ $options['queue'] = $commands['queueName'];
+ }
+
+ if (isset($commands['queueNameHardcoded']) && $commands['queueNameHardcoded']) {
+ $options['prefix_queue'] = false;
+ }
+
$routeCollection->add(new Route($source, Route::COMMAND, $processor, $options));
- } else {
- throw new \LogicException(sprintf(
- 'Command subscriber configuration is invalid for "%s::getSubscribedCommand()". "%s"',
- $processorClass,
- json_encode($processorClass::getSubscribedCommand())
- ));
+
+ continue;
+ }
+
+ if (isset($commands['command'])) {
+ $commands = [$commands];
+ }
+
+ foreach ($commands as $key => $params) {
+ if (is_string($params)) {
+ $routeCollection->add(new Route($params, Route::COMMAND, $serviceId, ['processor_service_id' => $serviceId]));
+ } elseif (is_array($params)) {
+ $source = $params['command'] ?? null;
+ $processor = $params['processor'] ?? $serviceId;
+ unset($params['command'], $params['source'], $params['source_type'], $params['processor'], $params['options']);
+ $options = $params;
+ $options['processor_service_id'] = $serviceId;
+
+ $routeCollection->add(new Route($source, Route::COMMAND, $processor, $options));
+ } else {
+ throw new \LogicException(sprintf('Command subscriber configuration is invalid for "%s::getSubscribedCommand()". "%s"', $processorClass, json_encode($processorClass::getSubscribedCommand())));
+ }
}
}
}
- }
- $rawRoutes = $routeCollection->toArray();
+ $rawRoutes = $routeCollection->toArray();
- $routeCollectionService = $container->getDefinition($routeCollectionId);
- $routeCollectionService->replaceArgument(0, array_merge(
- $routeCollectionService->getArgument(0),
- $rawRoutes
- ));
+ $routeCollectionService = $container->getDefinition($routeCollectionId);
+ $routeCollectionService->replaceArgument(0, array_merge(
+ $routeCollectionService->getArgument(0),
+ $rawRoutes
+ ));
+ }
}
}
diff --git a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildConsumptionExtensionsPass.php b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildConsumptionExtensionsPass.php
index 8482225f2..274847c90 100644
--- a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildConsumptionExtensionsPass.php
+++ b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildConsumptionExtensionsPass.php
@@ -2,64 +2,62 @@
namespace Enqueue\Symfony\Client\DependencyInjection;
+use Enqueue\Symfony\DiUtils;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
final class BuildConsumptionExtensionsPass implements CompilerPassInterface
{
- /**
- * @var string
- */
- private $name;
-
- public function __construct(string $clientName)
+ public function process(ContainerBuilder $container): void
{
- if (empty($clientName)) {
- throw new \InvalidArgumentException('The name could not be empty.');
+ if (false == $container->hasParameter('enqueue.clients')) {
+ throw new \LogicException('The "enqueue.clients" parameter must be set.');
}
- $this->name = $clientName;
- }
+ $names = $container->getParameter('enqueue.clients');
+ $defaultName = $container->getParameter('enqueue.default_client');
- public function process(ContainerBuilder $container): void
- {
- $extensionsId = sprintf('enqueue.client.%s.consumption_extensions', $this->name);
- if (false == $container->hasDefinition($extensionsId)) {
- return;
- }
+ foreach ($names as $name) {
+ $diUtils = DiUtils::create(ClientFactory::MODULE, $name);
+
+ $extensionsId = $diUtils->format('consumption_extensions');
+ if (false == $container->hasDefinition($extensionsId)) {
+ throw new \LogicException(sprintf('Service "%s" not found', $extensionsId));
+ }
- $tags = array_merge(
- $container->findTaggedServiceIds('enqueue.consumption_extension'),
- $container->findTaggedServiceIds('enqueue.consumption.extension') // TODO BC
- );
+ $tags = array_merge(
+ $container->findTaggedServiceIds('enqueue.consumption_extension'),
+ $container->findTaggedServiceIds('enqueue.consumption.extension') // TODO BC
+ );
- $groupByPriority = [];
- foreach ($tags as $serviceId => $tagAttributes) {
- foreach ($tagAttributes as $tagAttribute) {
- $client = $tagAttribute['client'] ?? 'default';
+ $groupByPriority = [];
+ foreach ($tags as $serviceId => $tagAttributes) {
+ foreach ($tagAttributes as $tagAttribute) {
+ $client = $tagAttribute['client'] ?? $defaultName;
- if ($client !== $this->name && 'all' !== $client) {
- continue;
- }
+ if ($client !== $name && 'all' !== $client) {
+ continue;
+ }
- $priority = (int) ($tagAttribute['priority'] ?? 0);
+ $priority = (int) ($tagAttribute['priority'] ?? 0);
- $groupByPriority[$priority][] = new Reference($serviceId);
+ $groupByPriority[$priority][] = new Reference($serviceId);
+ }
}
- }
- krsort($groupByPriority, SORT_NUMERIC);
+ krsort($groupByPriority, \SORT_NUMERIC);
- $flatExtensions = [];
- foreach ($groupByPriority as $extension) {
- $flatExtensions = array_merge($flatExtensions, $extension);
- }
+ $flatExtensions = [];
+ foreach ($groupByPriority as $extension) {
+ $flatExtensions = array_merge($flatExtensions, $extension);
+ }
- $extensionsService = $container->getDefinition($extensionsId);
- $extensionsService->replaceArgument(0, array_merge(
- $extensionsService->getArgument(0),
- $flatExtensions
- ));
+ $extensionsService = $container->getDefinition($extensionsId);
+ $extensionsService->replaceArgument(0, array_merge(
+ $extensionsService->getArgument(0),
+ $flatExtensions
+ ));
+ }
}
}
diff --git a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildProcessorRegistryPass.php b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildProcessorRegistryPass.php
index d69935d64..3759dd209 100644
--- a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildProcessorRegistryPass.php
+++ b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildProcessorRegistryPass.php
@@ -3,6 +3,7 @@
namespace Enqueue\Symfony\Client\DependencyInjection;
use Enqueue\Client\RouteCollection;
+use Enqueue\Symfony\DiUtils;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
@@ -10,51 +11,47 @@
final class BuildProcessorRegistryPass implements CompilerPassInterface
{
- /**
- * @var string
- */
- private $name;
-
- public function __construct(string $clientName)
- {
- if (empty($clientName)) {
- throw new \InvalidArgumentException('The name could not be empty.');
- }
-
- $this->name = $clientName;
- }
-
public function process(ContainerBuilder $container): void
{
- $processorRegistryId = sprintf('enqueue.client.%s.processor_registry', $this->name);
- if (false == $container->hasDefinition($processorRegistryId)) {
- return;
+ if (false == $container->hasParameter('enqueue.clients')) {
+ throw new \LogicException('The "enqueue.clients" parameter must be set.');
}
- $routeCollectionId = sprintf('enqueue.client.%s.route_collection', $this->name);
- if (false == $container->hasDefinition($routeCollectionId)) {
- return;
- }
+ $names = $container->getParameter('enqueue.clients');
- $routerProcessorId = sprintf('enqueue.client.%s.router_processor', $this->name);
- if (false == $container->hasDefinition($routerProcessorId)) {
- return;
- }
+ foreach ($names as $name) {
+ $diUtils = DiUtils::create(ClientFactory::MODULE, $name);
- $routeCollection = RouteCollection::fromArray($container->getDefinition($routeCollectionId)->getArgument(0));
+ $processorRegistryId = $diUtils->format('processor_registry');
+ if (false == $container->hasDefinition($processorRegistryId)) {
+ throw new \LogicException(sprintf('Service "%s" not found', $processorRegistryId));
+ }
- $map = [];
- foreach ($routeCollection->all() as $route) {
- if (false == $processorServiceId = $route->getOption('processor_service_id')) {
- throw new \LogicException('The route option "processor_service_id" is required');
+ $routeCollectionId = $diUtils->format('route_collection');
+ if (false == $container->hasDefinition($routeCollectionId)) {
+ throw new \LogicException(sprintf('Service "%s" not found', $routeCollectionId));
}
- $map[$route->getProcessor()] = new Reference($processorServiceId);
- }
+ $routerProcessorId = $diUtils->format('router_processor');
+ if (false == $container->hasDefinition($routerProcessorId)) {
+ throw new \LogicException(sprintf('Service "%s" not found', $routerProcessorId));
+ }
+
+ $routeCollection = RouteCollection::fromArray($container->getDefinition($routeCollectionId)->getArgument(0));
- $map["%enqueue.client.{$this->name}.router_processor%"] = new Reference($routerProcessorId);
+ $map = [];
+ foreach ($routeCollection->all() as $route) {
+ if (false == $processorServiceId = $route->getOption('processor_service_id')) {
+ throw new \LogicException('The route option "processor_service_id" is required');
+ }
- $registry = $container->getDefinition($processorRegistryId);
- $registry->setArgument(0, ServiceLocatorTagPass::register($container, $map, $processorRegistryId));
+ $map[$route->getProcessor()] = new Reference($processorServiceId);
+ }
+
+ $map[$diUtils->parameter('router_processor')] = new Reference($routerProcessorId);
+
+ $registry = $container->getDefinition($processorRegistryId);
+ $registry->setArgument(0, ServiceLocatorTagPass::register($container, $map, $processorRegistryId));
+ }
}
}
diff --git a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildProcessorRoutesPass.php b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildProcessorRoutesPass.php
index 415b87a92..e88cb1f83 100644
--- a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildProcessorRoutesPass.php
+++ b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildProcessorRoutesPass.php
@@ -4,77 +4,74 @@
use Enqueue\Client\Route;
use Enqueue\Client\RouteCollection;
+use Enqueue\Symfony\DiUtils;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
final class BuildProcessorRoutesPass implements CompilerPassInterface
{
- /**
- * @var string
- */
- private $name;
-
- public function __construct(string $clientName)
+ public function process(ContainerBuilder $container): void
{
- if (empty($clientName)) {
- throw new \InvalidArgumentException('The name could not be empty.');
+ if (false == $container->hasParameter('enqueue.clients')) {
+ throw new \LogicException('The "enqueue.clients" parameter must be set.');
}
- $this->name = $clientName;
- }
+ $names = $container->getParameter('enqueue.clients');
+ $defaultName = $container->getParameter('enqueue.default_client');
- public function process(ContainerBuilder $container): void
- {
- $routeCollectionId = sprintf('enqueue.client.%s.route_collection', $this->name);
- if (false == $container->hasDefinition($routeCollectionId)) {
- return;
- }
+ foreach ($names as $name) {
+ $diUtils = DiUtils::create(ClientFactory::MODULE, $name);
+ $routeCollectionId = $diUtils->format('route_collection');
+ if (false == $container->hasDefinition($routeCollectionId)) {
+ throw new \LogicException(sprintf('Service "%s" not found', $routeCollectionId));
+ }
- $tag = 'enqueue.processor';
- $routeCollection = new RouteCollection([]);
- foreach ($container->findTaggedServiceIds($tag) as $serviceId => $tagAttributes) {
- foreach ($tagAttributes as $tagAttribute) {
- $client = $tagAttribute['client'] ?? 'default';
+ $tag = 'enqueue.processor';
+ $routeCollection = new RouteCollection([]);
+ foreach ($container->findTaggedServiceIds($tag) as $serviceId => $tagAttributes) {
+ foreach ($tagAttributes as $tagAttribute) {
+ $client = $tagAttribute['client'] ?? $defaultName;
- if ($client !== $this->name && 'all' !== $client) {
- continue;
- }
+ if ($client !== $name && 'all' !== $client) {
+ continue;
+ }
- $topic = $tagAttribute['topic'] ?? null;
- $command = $tagAttribute['command'] ?? null;
+ $topic = $tagAttribute['topic'] ?? null;
+ $command = $tagAttribute['command'] ?? null;
- if (false == $topic && false == $command) {
- throw new \LogicException(sprintf('Either "topic" or "command" tag attribute must be set on service "%s". None is set.', $serviceId));
- }
- if ($topic && $command) {
- throw new \LogicException(sprintf('Either "topic" or "command" tag attribute must be set on service "%s". Both are set.', $serviceId));
- }
+ if (false == $topic && false == $command) {
+ throw new \LogicException(sprintf('Either "topic" or "command" tag attribute must be set on service "%s". None is set.', $serviceId));
+ }
+ if ($topic && $command) {
+ throw new \LogicException(sprintf('Either "topic" or "command" tag attribute must be set on service "%s". Both are set.', $serviceId));
+ }
- $source = $command ?: $topic;
- $sourceType = $command ? Route::COMMAND : Route::TOPIC;
- $processor = $tagAttribute['processor'] ?? $serviceId;
+ $source = $command ?: $topic;
+ $sourceType = $command ? Route::COMMAND : Route::TOPIC;
+ $processor = $tagAttribute['processor'] ?? $serviceId;
- unset(
- $tagAttribute['topic'],
- $tagAttribute['command'],
- $tagAttribute['source'],
- $tagAttribute['source_type'],
- $tagAttribute['processor'],
- $tagAttribute['options']
- );
- $options = $tagAttribute;
- $options['processor_service_id'] = $serviceId;
+ unset(
+ $tagAttribute['topic'],
+ $tagAttribute['command'],
+ $tagAttribute['source'],
+ $tagAttribute['source_type'],
+ $tagAttribute['processor'],
+ $tagAttribute['options']
+ );
+ $options = $tagAttribute;
+ $options['processor_service_id'] = $serviceId;
- $routeCollection->add(new Route($source, $sourceType, $processor, $options));
+ $routeCollection->add(new Route($source, $sourceType, $processor, $options));
+ }
}
- }
- $rawRoutes = $routeCollection->toArray();
+ $rawRoutes = $routeCollection->toArray();
- $routeCollectionService = $container->getDefinition($routeCollectionId);
- $routeCollectionService->replaceArgument(0, array_merge(
- $routeCollectionService->getArgument(0),
- $rawRoutes
- ));
+ $routeCollectionService = $container->getDefinition($routeCollectionId);
+ $routeCollectionService->replaceArgument(0, array_merge(
+ $routeCollectionService->getArgument(0),
+ $rawRoutes
+ ));
+ }
}
}
diff --git a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildTopicSubscriberRoutesPass.php b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildTopicSubscriberRoutesPass.php
index 73f3a019c..ef01e6fcf 100644
--- a/pkg/enqueue/Symfony/Client/DependencyInjection/BuildTopicSubscriberRoutesPass.php
+++ b/pkg/enqueue/Symfony/Client/DependencyInjection/BuildTopicSubscriberRoutesPass.php
@@ -5,99 +5,123 @@
use Enqueue\Client\Route;
use Enqueue\Client\RouteCollection;
use Enqueue\Client\TopicSubscriberInterface;
+use Enqueue\Symfony\DiUtils;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
final class BuildTopicSubscriberRoutesPass implements CompilerPassInterface
{
- /**
- * @var string
- */
- private $name;
-
- public function __construct(string $clientName)
- {
- if (empty($clientName)) {
- throw new \InvalidArgumentException('The name could not be empty.');
- }
-
- $this->name = $clientName;
- }
-
public function process(ContainerBuilder $container): void
{
- $routeCollectionId = sprintf('enqueue.client.%s.route_collection', $this->name);
- if (false == $container->hasDefinition($routeCollectionId)) {
- return;
+ if (false == $container->hasParameter('enqueue.clients')) {
+ throw new \LogicException('The "enqueue.clients" parameter must be set.');
}
- $tag = 'enqueue.topic_subscriber';
- $routeCollection = new RouteCollection([]);
- foreach ($container->findTaggedServiceIds($tag) as $serviceId => $tagAttributes) {
- $processorDefinition = $container->getDefinition($serviceId);
- if ($processorDefinition->getFactory()) {
- throw new \LogicException('The topic subscriber tag could not be applied to a service created by factory.');
- }
+ $names = $container->getParameter('enqueue.clients');
+ $defaultName = $container->getParameter('enqueue.default_client');
- $processorClass = $processorDefinition->getClass();
- if (false == class_exists($processorClass)) {
- throw new \LogicException(sprintf('The processor class "%s" could not be found.', $processorClass));
+ foreach ($names as $name) {
+ $diUtils = DiUtils::create(ClientFactory::MODULE, $name);
+ $routeCollectionId = $diUtils->format('route_collection');
+ if (false == $container->hasDefinition($routeCollectionId)) {
+ throw new \LogicException(sprintf('Service "%s" not found', $routeCollectionId));
}
- if (false == is_subclass_of($processorClass, TopicSubscriberInterface::class)) {
- throw new \LogicException(sprintf('The processor must implement "%s" interface to be used with the tag "%s"', TopicSubscriberInterface::class, $tag));
- }
+ $tag = 'enqueue.topic_subscriber';
+ $routeCollection = new RouteCollection([]);
+ foreach ($container->findTaggedServiceIds($tag) as $serviceId => $tagAttributes) {
+ $processorDefinition = $container->getDefinition($serviceId);
+ if ($processorDefinition->getFactory()) {
+ throw new \LogicException('The topic subscriber tag could not be applied to a service created by factory.');
+ }
- foreach ($tagAttributes as $tagAttribute) {
- $client = $tagAttribute['client'] ?? 'default';
+ $processorClass = $processorDefinition->getClass() ?? $serviceId;
+ if (false == class_exists($processorClass)) {
+ throw new \LogicException(sprintf('The processor class "%s" could not be found.', $processorClass));
+ }
- if ($client !== $this->name && 'all' !== $client) {
- continue;
+ if (false == is_subclass_of($processorClass, TopicSubscriberInterface::class)) {
+ throw new \LogicException(sprintf('The processor must implement "%s" interface to be used with the tag "%s"', TopicSubscriberInterface::class, $tag));
}
- /** @var TopicSubscriberInterface $processorClass */
- $topics = $processorClass::getSubscribedTopics();
+ foreach ($tagAttributes as $tagAttribute) {
+ $client = $tagAttribute['client'] ?? $defaultName;
- if (empty($topics)) {
- throw new \LogicException('Topic subscriber must return something.');
- }
+ if ($client !== $name && 'all' !== $client) {
+ continue;
+ }
- if (is_string($topics)) {
- $topics = [$topics];
- }
+ /** @var TopicSubscriberInterface $processorClass */
+ $topics = $processorClass::getSubscribedTopics();
- if (!is_array($topics)) {
- throw new \LogicException('Topic subscriber configuration is invalid. Should be an array or string.');
- }
+ if (empty($topics)) {
+ throw new \LogicException('Topic subscriber must return something.');
+ }
+
+ if (is_string($topics)) {
+ $topics = [$topics];
+ }
+
+ if (!is_array($topics)) {
+ throw new \LogicException('Topic subscriber configuration is invalid. Should be an array or string.');
+ }
- foreach ($topics as $key => $params) {
- if (is_string($params)) {
- $routeCollection->add(new Route($params, Route::TOPIC, $serviceId, ['processor_service_id' => $serviceId]));
- } elseif (is_array($params)) {
- $source = $params['topic'] ?? null;
- $processor = $params['processor'] ?? $serviceId;
- unset($params['topic'], $params['source'], $params['source_type'], $params['processor'], $params['options']);
- $options = $params;
- $options['processor_service_id'] = $serviceId;
-
- $routeCollection->add(new Route($source, Route::TOPIC, $processor, $options));
- } else {
- throw new \LogicException(sprintf(
- 'Topic subscriber configuration is invalid for "%s::getSubscribedTopics()". Got "%s"',
- $processorClass,
- json_encode($processorClass::getSubscribedTopics())
- ));
+ foreach ($topics as $key => $params) {
+ if (is_string($params)) {
+ $routeCollection->add(new Route($params, Route::TOPIC, $serviceId, ['processor_service_id' => $serviceId]));
+
+ // 0.8 topic subscriber
+ } elseif (is_array($params) && is_string($key)) {
+ @trigger_error('The topic subscriber 0.8 syntax is deprecated since Enqueue 0.9.', \E_USER_DEPRECATED);
+
+ $source = $key;
+ $processor = $params['processorName'] ?? $serviceId;
+
+ $options = $params;
+ unset(
+ $options['processorName'],
+ $options['queueName'],
+ $options['queueNameHardcoded'],
+ $options['topic'],
+ $options['source'],
+ $options['source_type'],
+ $options['processor'],
+ $options['options']
+ );
+
+ $options['processor_service_id'] = $serviceId;
+
+ if (isset($params['queueName'])) {
+ $options['queue'] = $params['queueName'];
+ }
+
+ if (isset($params['queueNameHardcoded']) && $params['queueNameHardcoded']) {
+ $options['prefix_queue'] = false;
+ }
+
+ $routeCollection->add(new Route($source, Route::TOPIC, $processor, $options));
+ } elseif (is_array($params)) {
+ $source = $params['topic'] ?? null;
+ $processor = $params['processor'] ?? $serviceId;
+ unset($params['topic'], $params['source'], $params['source_type'], $params['processor'], $params['options']);
+ $options = $params;
+ $options['processor_service_id'] = $serviceId;
+
+ $routeCollection->add(new Route($source, Route::TOPIC, $processor, $options));
+ } else {
+ throw new \LogicException(sprintf('Topic subscriber configuration is invalid for "%s::getSubscribedTopics()". Got "%s"', $processorClass, json_encode($processorClass::getSubscribedTopics())));
+ }
}
}
}
- }
- $rawRoutes = $routeCollection->toArray();
+ $rawRoutes = $routeCollection->toArray();
- $routeCollectionService = $container->getDefinition($routeCollectionId);
- $routeCollectionService->replaceArgument(0, array_merge(
- $routeCollectionService->getArgument(0),
- $rawRoutes
- ));
+ $routeCollectionService = $container->getDefinition($routeCollectionId);
+ $routeCollectionService->replaceArgument(0, array_merge(
+ $routeCollectionService->getArgument(0),
+ $rawRoutes
+ ));
+ }
}
}
diff --git a/pkg/enqueue/Symfony/Client/DependencyInjection/ClientFactory.php b/pkg/enqueue/Symfony/Client/DependencyInjection/ClientFactory.php
new file mode 100644
index 000000000..be020dcff
--- /dev/null
+++ b/pkg/enqueue/Symfony/Client/DependencyInjection/ClientFactory.php
@@ -0,0 +1,254 @@
+default = $default;
+ $this->diUtils = DiUtils::create(self::MODULE, $name);
+ }
+
+ public static function getConfiguration(bool $debug, string $name = 'client'): NodeDefinition
+ {
+ $builder = new ArrayNodeDefinition($name);
+
+ $builder->children()
+ ->booleanNode('traceable_producer')->defaultValue($debug)->end()
+ ->scalarNode('prefix')->defaultValue('enqueue')->end()
+ ->scalarNode('separator')->defaultValue('.')->end()
+ ->scalarNode('app_name')->defaultValue('app')->end()
+ ->scalarNode('router_topic')->defaultValue('default')->cannotBeEmpty()->end()
+ ->scalarNode('router_queue')->defaultValue('default')->cannotBeEmpty()->end()
+ ->scalarNode('router_processor')->defaultNull()->end()
+ ->integerNode('redelivered_delay_time')->min(0)->defaultValue(0)->end()
+ ->scalarNode('default_queue')->defaultValue('default')->cannotBeEmpty()->end()
+ ->arrayNode('driver_options')->addDefaultsIfNotSet()->info('The array contains driver specific options')->ignoreExtraKeys(false)->end()
+ ->end()
+ ;
+
+ return $builder;
+ }
+
+ public function build(ContainerBuilder $container, array $config): void
+ {
+ $container->register($this->diUtils->format('context'), Context::class)
+ ->setFactory([$this->diUtils->reference('driver'), 'getContext'])
+ ;
+
+ $container->register($this->diUtils->format('driver_factory'), DriverFactory::class);
+
+ $routerProcessor = empty($config['router_processor'])
+ ? $this->diUtils->format('router_processor')
+ : $config['router_processor']
+ ;
+
+ $container->register($this->diUtils->format('config'), Config::class)
+ ->setArguments([
+ $config['prefix'],
+ $config['separator'],
+ $config['app_name'],
+ $config['router_topic'],
+ $config['router_queue'],
+ $config['default_queue'],
+ $routerProcessor,
+ $config['transport'],
+ $config['driver_options'] ?? [],
+ ]);
+
+ $container->setParameter($this->diUtils->format('router_processor'), $routerProcessor);
+ $container->setParameter($this->diUtils->format('router_queue_name'), $config['router_queue']);
+ $container->setParameter($this->diUtils->format('default_queue_name'), $config['default_queue']);
+
+ $container->register($this->diUtils->format('route_collection'), RouteCollection::class)
+ ->addArgument([])
+ ->setFactory([RouteCollection::class, 'fromArray'])
+ ;
+
+ $container->register($this->diUtils->format('producer'), Producer::class)
+ // @deprecated
+ ->setPublic(true)
+ ->addArgument($this->diUtils->reference('driver'))
+ ->addArgument($this->diUtils->reference('rpc_factory'))
+ ->addArgument($this->diUtils->reference('client_extensions'))
+ ;
+
+ $lazyProducer = $container->register($this->diUtils->format('lazy_producer'), LazyProducer::class);
+ $lazyProducer->addArgument(ServiceLocatorTagPass::register($container, [
+ $this->diUtils->format('producer') => new Reference($this->diUtils->format('producer')),
+ ]));
+ $lazyProducer->addArgument($this->diUtils->format('producer'));
+
+ $container->register($this->diUtils->format('spool_producer'), SpoolProducer::class)
+ ->addArgument($this->diUtils->reference('lazy_producer'))
+ ;
+
+ $container->register($this->diUtils->format('client_extensions'), ChainExtension::class)
+ ->addArgument([])
+ ;
+
+ $container->register($this->diUtils->format('rpc_factory'), RpcFactory::class)
+ ->addArgument($this->diUtils->reference('context'))
+ ;
+
+ $container->register($this->diUtils->format('router_processor'), RouterProcessor::class)
+ ->addArgument($this->diUtils->reference('driver'))
+ ;
+
+ $container->register($this->diUtils->format('processor_registry'), ContainerProcessorRegistry::class);
+
+ $container->register($this->diUtils->format('delegate_processor'), DelegateProcessor::class)
+ ->addArgument($this->diUtils->reference('processor_registry'))
+ ;
+
+ $container->register($this->diUtils->format('set_router_properties_extension'), SetRouterPropertiesExtension::class)
+ ->addArgument($this->diUtils->reference('driver'))
+ ->addTag('enqueue.consumption_extension', ['priority' => 100, 'client' => $this->diUtils->getConfigName()])
+ ;
+
+ $container->register($this->diUtils->format('queue_consumer'), QueueConsumer::class)
+ ->addArgument($this->diUtils->reference('context'))
+ ->addArgument($this->diUtils->reference('consumption_extensions'))
+ ->addArgument([])
+ ->addArgument(new Reference('logger', ContainerInterface::NULL_ON_INVALID_REFERENCE))
+ ->addArgument($config['consumption']['receive_timeout'])
+ ;
+
+ $container->register($this->diUtils->format('consumption_extensions'), ConsumptionChainExtension::class)
+ ->addArgument([])
+ ;
+
+ $container->register($this->diUtils->format('flush_spool_producer_extension'), FlushSpoolProducerExtension::class)
+ ->addArgument($this->diUtils->reference('spool_producer'))
+ ->addTag('enqueue.consumption.extension', ['priority' => -100, 'client' => $this->diUtils->getConfigName()])
+ ;
+
+ $container->register($this->diUtils->format('exclusive_command_extension'), ExclusiveCommandExtension::class)
+ ->addArgument($this->diUtils->reference('driver'))
+ ->addTag('enqueue.consumption.extension', ['priority' => 100, 'client' => $this->diUtils->getConfigName()])
+ ;
+
+ if ($config['traceable_producer']) {
+ $container->register($this->diUtils->format('traceable_producer'), TraceableProducer::class)
+ ->setDecoratedService($this->diUtils->format('producer'))
+ ->addArgument($this->diUtils->reference('traceable_producer.inner'))
+ ;
+ }
+
+ if ($config['redelivered_delay_time']) {
+ $container->register($this->diUtils->format('delay_redelivered_message_extension'), DelayRedeliveredMessageExtension::class)
+ ->addArgument($this->diUtils->reference('driver'))
+ ->addArgument($config['redelivered_delay_time'])
+ ->addTag('enqueue.consumption_extension', ['priority' => 10, 'client' => $this->diUtils->getConfigName()])
+ ;
+
+ $container->getDefinition($this->diUtils->format('delay_redelivered_message_extension'))
+ ->replaceArgument(1, $config['redelivered_delay_time'])
+ ;
+ }
+
+ $locatorId = 'enqueue.locator';
+ if ($container->hasDefinition($locatorId)) {
+ $locator = $container->getDefinition($locatorId);
+ $locator->replaceArgument(0, array_replace($locator->getArgument(0), [
+ $this->diUtils->format('queue_consumer') => $this->diUtils->reference('queue_consumer'),
+ $this->diUtils->format('driver') => $this->diUtils->reference('driver'),
+ $this->diUtils->format('delegate_processor') => $this->diUtils->reference('delegate_processor'),
+ $this->diUtils->format('producer') => $this->diUtils->reference('lazy_producer'),
+ ]));
+ }
+
+ if ($this->default) {
+ $container->setAlias(ProducerInterface::class, $this->diUtils->format('lazy_producer'));
+ $container->setAlias(SpoolProducer::class, $this->diUtils->format('spool_producer'));
+
+ if (DiUtils::DEFAULT_CONFIG !== $this->diUtils->getConfigName()) {
+ $container->setAlias($this->diUtils->formatDefault('producer'), $this->diUtils->format('producer'));
+ $container->setAlias($this->diUtils->formatDefault('spool_producer'), $this->diUtils->format('spool_producer'));
+ }
+ }
+ }
+
+ public function createDriver(ContainerBuilder $container, array $config): string
+ {
+ $factoryId = DiUtils::create(TransportFactory::MODULE, $this->diUtils->getConfigName())->format('connection_factory');
+ $driverId = $this->diUtils->format('driver');
+ $driverFactoryId = $this->diUtils->format('driver_factory');
+
+ $container->register($driverId, DriverInterface::class)
+ ->setFactory([new Reference($driverFactoryId), 'create'])
+ ->addArgument(new Reference($factoryId))
+ ->addArgument($this->diUtils->reference('config'))
+ ->addArgument($this->diUtils->reference('route_collection'))
+ ;
+
+ if ($this->default) {
+ $container->setAlias(DriverInterface::class, $driverId);
+
+ if (DiUtils::DEFAULT_CONFIG !== $this->diUtils->getConfigName()) {
+ $container->setAlias($this->diUtils->formatDefault('driver'), $driverId);
+ }
+ }
+
+ return $driverId;
+ }
+
+ public function createFlushSpoolProducerListener(ContainerBuilder $container): void
+ {
+ $container->register($this->diUtils->format('flush_spool_producer_listener'), FlushSpoolProducerListener::class)
+ ->addArgument($this->diUtils->reference('spool_producer'))
+ ->addTag('kernel.event_subscriber')
+ ;
+ }
+}
diff --git a/pkg/enqueue/Symfony/Client/FlushSpoolProducerListener.php b/pkg/enqueue/Symfony/Client/FlushSpoolProducerListener.php
index 1f5fdcba7..00543f6de 100644
--- a/pkg/enqueue/Symfony/Client/FlushSpoolProducerListener.php
+++ b/pkg/enqueue/Symfony/Client/FlushSpoolProducerListener.php
@@ -14,9 +14,6 @@ class FlushSpoolProducerListener implements EventSubscriberInterface
*/
private $producer;
- /**
- * @param SpoolProducer $producer
- */
public function __construct(SpoolProducer $producer)
{
$this->producer = $producer;
@@ -27,10 +24,7 @@ public function flushMessages()
$this->producer->flush();
}
- /**
- * {@inheritdoc}
- */
- public static function getSubscribedEvents()
+ public static function getSubscribedEvents(): array
{
$events = [];
diff --git a/pkg/enqueue/Symfony/Client/LazyProducer.php b/pkg/enqueue/Symfony/Client/LazyProducer.php
new file mode 100644
index 000000000..8dd3aadba
--- /dev/null
+++ b/pkg/enqueue/Symfony/Client/LazyProducer.php
@@ -0,0 +1,37 @@
+container = $container;
+ $this->producerId = $producerId;
+ }
+
+ public function sendEvent(string $topic, $message): void
+ {
+ $this->getRealProducer()->sendEvent($topic, $message);
+ }
+
+ public function sendCommand(string $command, $message, bool $needReply = false): ?Promise
+ {
+ return $this->getRealProducer()->sendCommand($command, $message, $needReply);
+ }
+
+ private function getRealProducer(): ProducerInterface
+ {
+ return $this->container->get($this->producerId);
+ }
+}
diff --git a/pkg/enqueue/Symfony/Client/ProduceCommand.php b/pkg/enqueue/Symfony/Client/ProduceCommand.php
index 302b344c7..953a76687 100644
--- a/pkg/enqueue/Symfony/Client/ProduceCommand.php
+++ b/pkg/enqueue/Symfony/Client/ProduceCommand.php
@@ -2,35 +2,42 @@
namespace Enqueue\Symfony\Client;
+use Enqueue\Client\Message;
use Enqueue\Client\ProducerInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
+#[AsCommand('enqueue:produce')]
class ProduceCommand extends Command
{
- protected static $defaultName = 'enqueue:produce';
-
/**
* @var ContainerInterface
*/
private $container;
+ /**
+ * @var string
+ */
+ private $defaultClient;
+
/**
* @var string
*/
private $producerIdPattern;
- public function __construct(ContainerInterface $container, string $producerIdPattern = 'enqueue.client.%s.producer')
+ public function __construct(ContainerInterface $container, string $defaultClient, string $producerIdPattern = 'enqueue.client.%s.producer')
{
- parent::__construct(static::$defaultName);
-
$this->container = $container;
+ $this->defaultClient = $defaultClient;
$this->producerIdPattern = $producerIdPattern;
+
+ parent::__construct();
}
protected function configure(): void
@@ -38,17 +45,19 @@ protected function configure(): void
$this
->setDescription('Sends an event to the topic')
->addArgument('message', InputArgument::REQUIRED, 'A message')
- ->addOption('client', 'c', InputOption::VALUE_OPTIONAL, 'The client to consume messages from.', 'default')
+ ->addOption('header', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'The message headers')
+ ->addOption('client', 'c', InputOption::VALUE_OPTIONAL, 'The client to consume messages from.', $this->defaultClient)
->addOption('topic', null, InputOption::VALUE_OPTIONAL, 'The topic to send a message to')
->addOption('command', null, InputOption::VALUE_OPTIONAL, 'The command to send a message to')
;
}
- protected function execute(InputInterface $input, OutputInterface $output): ?int
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
$topic = $input->getOption('topic');
$command = $input->getOption('command');
$message = $input->getArgument('message');
+ $headers = (array) $input->getOption('header');
$client = $input->getOption('client');
if ($topic && $command) {
@@ -58,11 +67,11 @@ protected function execute(InputInterface $input, OutputInterface $output): ?int
try {
$producer = $this->getProducer($client);
} catch (NotFoundExceptionInterface $e) {
- throw new \LogicException(sprintf('Client "%s" is not supported.', $client), null, $e);
+ throw new \LogicException(sprintf('Client "%s" is not supported.', $client), previous: $e);
}
if ($topic) {
- $producer->sendEvent($topic, $message);
+ $producer->sendEvent($topic, new Message($message, [], $headers));
$output->writeln('An event is sent');
} elseif ($command) {
@@ -73,7 +82,7 @@ protected function execute(InputInterface $input, OutputInterface $output): ?int
throw new \LogicException('Either topic or command option should be set, none is set.');
}
- return null;
+ return 0;
}
private function getProducer(string $client): ProducerInterface
diff --git a/pkg/enqueue/Symfony/Client/RoutesCommand.php b/pkg/enqueue/Symfony/Client/RoutesCommand.php
index 82bcacf19..04b657ef7 100644
--- a/pkg/enqueue/Symfony/Client/RoutesCommand.php
+++ b/pkg/enqueue/Symfony/Client/RoutesCommand.php
@@ -6,6 +6,7 @@
use Enqueue\Client\Route;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Helper\TableSeparator;
@@ -13,15 +14,19 @@
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
+#[AsCommand('enqueue:routes')]
class RoutesCommand extends Command
{
- protected static $defaultName = 'enqueue:routes';
-
/**
* @var ContainerInterface
*/
private $container;
+ /**
+ * @var string
+ */
+ private $defaultClient;
+
/**
* @var string
*/
@@ -32,12 +37,13 @@ class RoutesCommand extends Command
*/
private $driver;
- public function __construct(ContainerInterface $container, string $driverIdPatter = 'enqueue.client.%s.driver')
+ public function __construct(ContainerInterface $container, string $defaultClient, string $driverIdPatter = 'enqueue.client.%s.driver')
{
- parent::__construct(static::$defaultName);
-
$this->container = $container;
+ $this->defaultClient = $defaultClient;
$this->driverIdPatter = $driverIdPatter;
+
+ parent::__construct();
}
protected function configure(): void
@@ -46,18 +52,18 @@ protected function configure(): void
->setAliases(['debug:enqueue:routes'])
->setDescription('A command lists all registered routes.')
->addOption('show-route-options', null, InputOption::VALUE_NONE, 'Adds ability to hide options.')
- ->addOption('client', 'c', InputOption::VALUE_OPTIONAL, 'The client to consume messages from.', 'default')
+ ->addOption('client', 'c', InputOption::VALUE_OPTIONAL, 'The client to consume messages from.', $this->defaultClient)
;
$this->driver = null;
}
- protected function execute(InputInterface $input, OutputInterface $output): ?int
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
try {
$this->driver = $this->getDriver($input->getOption('client'));
} catch (NotFoundExceptionInterface $e) {
- throw new \LogicException(sprintf('Client "%s" is not supported.', $input->getOption('client')), null, $e);
+ throw new \LogicException(sprintf('Client "%s" is not supported.', $input->getOption('client')), previous: $e);
}
$routes = $this->driver->getRouteCollection()->all();
@@ -106,7 +112,7 @@ protected function execute(InputInterface $input, OutputInterface $output): ?int
$table->render();
}
- return null;
+ return 0;
}
private function formatSourceType(Route $route): string
diff --git a/pkg/enqueue/Symfony/Client/SetupBrokerCommand.php b/pkg/enqueue/Symfony/Client/SetupBrokerCommand.php
index 4a4f322ec..92d5ad022 100644
--- a/pkg/enqueue/Symfony/Client/SetupBrokerCommand.php
+++ b/pkg/enqueue/Symfony/Client/SetupBrokerCommand.php
@@ -5,32 +5,38 @@
use Enqueue\Client\DriverInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
+#[AsCommand('enqueue:setup-broker')]
class SetupBrokerCommand extends Command
{
- protected static $defaultName = 'enqueue:setup-broker';
-
/**
* @var ContainerInterface
*/
private $container;
+ /**
+ * @var string
+ */
+ private $defaultClient;
+
/**
* @var string
*/
private $driverIdPattern;
- public function __construct(ContainerInterface $container, string $driverIdPattern = 'enqueue.client.%s.driver')
+ public function __construct(ContainerInterface $container, string $defaultClient, string $driverIdPattern = 'enqueue.client.%s.driver')
{
- parent::__construct(static::$defaultName);
-
$this->container = $container;
+ $this->defaultClient = $defaultClient;
$this->driverIdPattern = $driverIdPattern;
+
+ parent::__construct();
}
protected function configure(): void
@@ -38,23 +44,23 @@ protected function configure(): void
$this
->setAliases(['enq:sb'])
->setDescription('Setup broker. Configure the broker, creates queues, topics and so on.')
- ->addOption('client', 'c', InputOption::VALUE_OPTIONAL, 'The client to consume messages from.', 'default')
+ ->addOption('client', 'c', InputOption::VALUE_OPTIONAL, 'The client to consume messages from.', $this->defaultClient)
;
}
- protected function execute(InputInterface $input, OutputInterface $output): ?int
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
$client = $input->getOption('client');
try {
$this->getDriver($client)->setupBroker(new ConsoleLogger($output));
} catch (NotFoundExceptionInterface $e) {
- throw new \LogicException(sprintf('Client "%s" is not supported.', $client), null, $e);
+ throw new \LogicException(sprintf('Client "%s" is not supported.', $client), previous: $e);
}
$output->writeln('Broker set up');
- return null;
+ return 0;
}
private function getDriver(string $client): DriverInterface
diff --git a/pkg/enqueue/Symfony/Client/SetupBrokerExtensionCommandTrait.php b/pkg/enqueue/Symfony/Client/SetupBrokerExtensionCommandTrait.php
index 2888f5636..bcc4f7bb2 100644
--- a/pkg/enqueue/Symfony/Client/SetupBrokerExtensionCommandTrait.php
+++ b/pkg/enqueue/Symfony/Client/SetupBrokerExtensionCommandTrait.php
@@ -10,9 +10,6 @@
trait SetupBrokerExtensionCommandTrait
{
- /**
- * {@inheritdoc}
- */
protected function configureSetupBrokerExtension()
{
$this
@@ -21,10 +18,7 @@ protected function configureSetupBrokerExtension()
}
/**
- * @param InputInterface $input
- * @param DriverInterface $driver
- *
- * @return ExtensionInterface
+ * @return ExtensionInterface|null
*/
protected function getSetupBrokerExtension(InputInterface $input, DriverInterface $driver)
{
diff --git a/pkg/enqueue/Symfony/Client/SimpleConsumeCommand.php b/pkg/enqueue/Symfony/Client/SimpleConsumeCommand.php
new file mode 100644
index 000000000..fafc35d05
--- /dev/null
+++ b/pkg/enqueue/Symfony/Client/SimpleConsumeCommand.php
@@ -0,0 +1,26 @@
+ $queueConsumer,
+ 'driver' => $driver,
+ 'processor' => $processor,
+ ]),
+ 'default',
+ 'queue_consumer',
+ 'driver',
+ 'processor'
+ );
+ }
+}
diff --git a/pkg/enqueue/Symfony/Client/SimpleProduceCommand.php b/pkg/enqueue/Symfony/Client/SimpleProduceCommand.php
new file mode 100644
index 000000000..5d7f76533
--- /dev/null
+++ b/pkg/enqueue/Symfony/Client/SimpleProduceCommand.php
@@ -0,0 +1,18 @@
+ $producer]),
+ 'default',
+ 'producer'
+ );
+ }
+}
diff --git a/pkg/enqueue/Symfony/Client/SimpleRoutesCommand.php b/pkg/enqueue/Symfony/Client/SimpleRoutesCommand.php
new file mode 100644
index 000000000..0023f14ae
--- /dev/null
+++ b/pkg/enqueue/Symfony/Client/SimpleRoutesCommand.php
@@ -0,0 +1,18 @@
+ $driver]),
+ 'default',
+ 'driver'
+ );
+ }
+}
diff --git a/pkg/enqueue/Symfony/Client/SimpleSetupBrokerCommand.php b/pkg/enqueue/Symfony/Client/SimpleSetupBrokerCommand.php
new file mode 100644
index 000000000..aae19f84b
--- /dev/null
+++ b/pkg/enqueue/Symfony/Client/SimpleSetupBrokerCommand.php
@@ -0,0 +1,18 @@
+ $driver]),
+ 'default',
+ 'driver'
+ );
+ }
+}
diff --git a/pkg/enqueue/Symfony/Consumption/ConfigurableConsumeCommand.php b/pkg/enqueue/Symfony/Consumption/ConfigurableConsumeCommand.php
index 68ae6dae2..34cb66d57 100644
--- a/pkg/enqueue/Symfony/Consumption/ConfigurableConsumeCommand.php
+++ b/pkg/enqueue/Symfony/Consumption/ConfigurableConsumeCommand.php
@@ -8,25 +8,30 @@
use Enqueue\ProcessorRegistryInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
+#[AsCommand('enqueue:transport:consume')]
class ConfigurableConsumeCommand extends Command
{
+ use ChooseLoggerCommandTrait;
use LimitsExtensionsCommandTrait;
use QueueConsumerOptionsCommandTrait;
- use ChooseLoggerCommandTrait;
-
- protected static $defaultName = 'enqueue:transport:consume';
/**
* @var ContainerInterface
*/
private $container;
+ /**
+ * @var string
+ */
+ private $defaultTransport;
+
/**
* @var string
*/
@@ -39,14 +44,16 @@ class ConfigurableConsumeCommand extends Command
public function __construct(
ContainerInterface $container,
+ string $defaultTransport,
string $queueConsumerIdPattern = 'enqueue.transport.%s.queue_consumer',
- string $processorRegistryIdPattern = 'enqueue.transport.%s.processor_registry'
+ string $processorRegistryIdPattern = 'enqueue.transport.%s.processor_registry',
) {
- parent::__construct(static::$defaultName);
-
$this->container = $container;
+ $this->defaultTransport = $defaultTransport;
$this->queueConsumerIdPattern = $queueConsumerIdPattern;
$this->processorRegistryIdPattern = $processorRegistryIdPattern;
+
+ parent::__construct();
}
protected function configure(): void
@@ -61,18 +68,18 @@ protected function configure(): void
'and a message processor service')
->addArgument('processor', InputArgument::REQUIRED, 'A message processor.')
->addArgument('queues', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, 'A queue to consume from', [])
- ->addOption('transport', 't', InputOption::VALUE_OPTIONAL, 'The transport to consume messages from.', 'default')
+ ->addOption('transport', 't', InputOption::VALUE_OPTIONAL, 'The transport to consume messages from.', $this->defaultTransport)
;
}
- protected function execute(InputInterface $input, OutputInterface $output): ?int
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
$transport = $input->getOption('transport');
try {
$consumer = $this->getQueueConsumer($transport);
} catch (NotFoundExceptionInterface $e) {
- throw new \LogicException(sprintf('Transport "%s" is not supported.', $transport), null, $e);
+ throw new \LogicException(sprintf('Transport "%s" is not supported.', $transport), previous: $e);
}
$this->setQueueConsumerOptions($consumer, $input);
@@ -85,10 +92,7 @@ protected function execute(InputInterface $input, OutputInterface $output): ?int
}
if (empty($queues)) {
- throw new \LogicException(sprintf(
- 'The queue is not provided. The processor must implement "%s" interface and it must return not empty array of queues or a queue set using as a second argument.',
- QueueSubscriberInterface::class
- ));
+ throw new \LogicException(sprintf('The queue is not provided. The processor must implement "%s" interface and it must return not empty array of queues or a queue set using as a second argument.', QueueSubscriberInterface::class));
}
$extensions = $this->getLimitsExtensions($input, $output);
@@ -103,7 +107,7 @@ protected function execute(InputInterface $input, OutputInterface $output): ?int
$consumer->consume(new ChainExtension($extensions));
- return null;
+ return 0;
}
private function getQueueConsumer(string $name): QueueConsumerInterface
diff --git a/pkg/enqueue/Symfony/Consumption/ConsumeCommand.php b/pkg/enqueue/Symfony/Consumption/ConsumeCommand.php
index 632a7de17..b69ae7269 100644
--- a/pkg/enqueue/Symfony/Consumption/ConsumeCommand.php
+++ b/pkg/enqueue/Symfony/Consumption/ConsumeCommand.php
@@ -3,21 +3,22 @@
namespace Enqueue\Symfony\Consumption;
use Enqueue\Consumption\ChainExtension;
+use Enqueue\Consumption\Extension\ExitStatusExtension;
use Enqueue\Consumption\QueueConsumerInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
+#[AsCommand('enqueue:transport:consume')]
class ConsumeCommand extends Command
{
+ use ChooseLoggerCommandTrait;
use LimitsExtensionsCommandTrait;
use QueueConsumerOptionsCommandTrait;
- use ChooseLoggerCommandTrait;
-
- protected static $defaultName = 'enqueue:transport:consume';
/**
* @var ContainerInterface
@@ -27,19 +28,20 @@ class ConsumeCommand extends Command
/**
* @var string
*/
- private $queueConsumerIdPattern;
+ private $defaultTransport;
/**
- * [name => QueueConsumerInterface].
- *
- * @param QueueConsumerInterface[]
+ * @var string
*/
- public function __construct(ContainerInterface $container, string $queueConsumerIdPattern = 'enqueue.transport.%s.queue_consumer')
- {
- parent::__construct(static::$defaultName);
+ private $queueConsumerIdPattern;
+ public function __construct(ContainerInterface $container, string $defaultTransport, string $queueConsumerIdPattern = 'enqueue.transport.%s.queue_consumer')
+ {
$this->container = $container;
+ $this->defaultTransport = $defaultTransport;
$this->queueConsumerIdPattern = $queueConsumerIdPattern;
+
+ parent::__construct();
}
protected function configure(): void
@@ -49,13 +51,13 @@ protected function configure(): void
$this->configureLoggerExtension();
$this
- ->addOption('transport', 't', InputOption::VALUE_OPTIONAL, 'The transport to consume messages from.', 'default')
+ ->addOption('transport', 't', InputOption::VALUE_OPTIONAL, 'The transport to consume messages from.', $this->defaultTransport)
->setDescription('A worker that consumes message from a broker. '.
'To use this broker you have to configure queue consumer before adding to the command')
;
}
- protected function execute(InputInterface $input, OutputInterface $output): ?int
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
$transport = $input->getOption('transport');
@@ -63,7 +65,7 @@ protected function execute(InputInterface $input, OutputInterface $output): ?int
// QueueConsumer must be pre configured outside of the command!
$consumer = $this->getQueueConsumer($transport);
} catch (NotFoundExceptionInterface $e) {
- throw new \LogicException(sprintf('Transport "%s" is not supported.', $transport), null, $e);
+ throw new \LogicException(sprintf('Transport "%s" is not supported.', $transport), previous: $e);
}
$this->setQueueConsumerOptions($consumer, $input);
@@ -74,9 +76,12 @@ protected function execute(InputInterface $input, OutputInterface $output): ?int
array_unshift($extensions, $loggerExtension);
}
+ $exitStatusExtension = new ExitStatusExtension();
+ array_unshift($extensions, $exitStatusExtension);
+
$consumer->consume(new ChainExtension($extensions));
- return null;
+ return $exitStatusExtension->getExitStatus() ?? 0;
}
private function getQueueConsumer(string $name): QueueConsumerInterface
diff --git a/pkg/enqueue/Symfony/Consumption/LimitsExtensionsCommandTrait.php b/pkg/enqueue/Symfony/Consumption/LimitsExtensionsCommandTrait.php
index b721af925..d8351acc5 100644
--- a/pkg/enqueue/Symfony/Consumption/LimitsExtensionsCommandTrait.php
+++ b/pkg/enqueue/Symfony/Consumption/LimitsExtensionsCommandTrait.php
@@ -23,9 +23,6 @@ protected function configureLimitsExtensions()
}
/**
- * @param InputInterface $input
- * @param OutputInterface $output
- *
* @throws \Exception
*
* @return ExtensionInterface[]
@@ -58,8 +55,8 @@ protected function getLimitsExtensions(InputInterface $input, OutputInterface $o
}
$niceness = $input->getOption('niceness');
- if ($niceness) {
- $extensions[] = new NicenessExtension($niceness);
+ if (!empty($niceness) && is_numeric($niceness)) {
+ $extensions[] = new NicenessExtension((int) $niceness);
}
return $extensions;
diff --git a/pkg/enqueue/Symfony/Consumption/QueueConsumerOptionsCommandTrait.php b/pkg/enqueue/Symfony/Consumption/QueueConsumerOptionsCommandTrait.php
index 9df852df9..fd736f226 100644
--- a/pkg/enqueue/Symfony/Consumption/QueueConsumerOptionsCommandTrait.php
+++ b/pkg/enqueue/Symfony/Consumption/QueueConsumerOptionsCommandTrait.php
@@ -8,9 +8,6 @@
trait QueueConsumerOptionsCommandTrait
{
- /**
- * {@inheritdoc}
- */
protected function configureQueueConsumerOptions()
{
$this
@@ -18,10 +15,6 @@ protected function configureQueueConsumerOptions()
;
}
- /**
- * @param QueueConsumerInterface $consumer
- * @param InputInterface $input
- */
protected function setQueueConsumerOptions(QueueConsumerInterface $consumer, InputInterface $input)
{
if (null !== $receiveTimeout = $input->getOption('receive-timeout')) {
diff --git a/pkg/enqueue/Symfony/Consumption/SimpleConsumeCommand.php b/pkg/enqueue/Symfony/Consumption/SimpleConsumeCommand.php
new file mode 100644
index 000000000..90d0e362e
--- /dev/null
+++ b/pkg/enqueue/Symfony/Consumption/SimpleConsumeCommand.php
@@ -0,0 +1,18 @@
+ $consumer]),
+ 'default',
+ 'queue_consumer'
+ );
+ }
+}
diff --git a/pkg/enqueue/Symfony/DependencyInjection/BuildConsumptionExtensionsPass.php b/pkg/enqueue/Symfony/DependencyInjection/BuildConsumptionExtensionsPass.php
index f9a6a470b..99f274ec5 100644
--- a/pkg/enqueue/Symfony/DependencyInjection/BuildConsumptionExtensionsPass.php
+++ b/pkg/enqueue/Symfony/DependencyInjection/BuildConsumptionExtensionsPass.php
@@ -2,61 +2,59 @@
namespace Enqueue\Symfony\DependencyInjection;
+use Enqueue\Symfony\DiUtils;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
final class BuildConsumptionExtensionsPass implements CompilerPassInterface
{
- /**
- * @var string
- */
- private $name;
-
- public function __construct(string $transportName)
+ public function process(ContainerBuilder $container): void
{
- if (empty($transportName)) {
- throw new \InvalidArgumentException('The name could not be empty.');
+ if (false == $container->hasParameter('enqueue.transports')) {
+ throw new \LogicException('The "enqueue.transports" parameter must be set.');
}
- $this->name = $transportName;
- }
+ $names = $container->getParameter('enqueue.transports');
+ $defaultName = $container->getParameter('enqueue.default_transport');
- public function process(ContainerBuilder $container): void
- {
- $extensionsId = sprintf('enqueue.transport.%s.consumption_extensions', $this->name);
- if (false == $container->hasDefinition($extensionsId)) {
- return;
- }
+ foreach ($names as $name) {
+ $diUtils = DiUtils::create(TransportFactory::MODULE, $name);
+
+ $extensionsId = $diUtils->format('consumption_extensions');
+ if (false == $container->hasDefinition($extensionsId)) {
+ throw new \LogicException(sprintf('Service "%s" not found', $extensionsId));
+ }
- $tags = $container->findTaggedServiceIds('enqueue.transport.consumption_extension');
+ $tags = $container->findTaggedServiceIds('enqueue.transport.consumption_extension');
- $groupByPriority = [];
- foreach ($tags as $serviceId => $tagAttributes) {
- foreach ($tagAttributes as $tagAttribute) {
- $transport = $tagAttribute['transport'] ?? 'default';
+ $groupByPriority = [];
+ foreach ($tags as $serviceId => $tagAttributes) {
+ foreach ($tagAttributes as $tagAttribute) {
+ $transport = $tagAttribute['transport'] ?? $defaultName;
- if ($transport !== $this->name && 'all' !== $transport) {
- continue;
- }
+ if ($transport !== $name && 'all' !== $transport) {
+ continue;
+ }
- $priority = (int) ($tagAttribute['priority'] ?? 0);
+ $priority = (int) ($tagAttribute['priority'] ?? 0);
- $groupByPriority[$priority][] = new Reference($serviceId);
+ $groupByPriority[$priority][] = new Reference($serviceId);
+ }
}
- }
- krsort($groupByPriority, SORT_NUMERIC);
+ krsort($groupByPriority, \SORT_NUMERIC);
- $flatExtensions = [];
- foreach ($groupByPriority as $extension) {
- $flatExtensions = array_merge($flatExtensions, $extension);
- }
+ $flatExtensions = [];
+ foreach ($groupByPriority as $extension) {
+ $flatExtensions = array_merge($flatExtensions, $extension);
+ }
- $extensionsService = $container->getDefinition($extensionsId);
- $extensionsService->replaceArgument(0, array_merge(
- $extensionsService->getArgument(0),
- $flatExtensions
- ));
+ $extensionsService = $container->getDefinition($extensionsId);
+ $extensionsService->replaceArgument(0, array_merge(
+ $extensionsService->getArgument(0),
+ $flatExtensions
+ ));
+ }
}
}
diff --git a/pkg/enqueue/Symfony/DependencyInjection/BuildProcessorRegistryPass.php b/pkg/enqueue/Symfony/DependencyInjection/BuildProcessorRegistryPass.php
index 8493dc7f9..cc6e04270 100644
--- a/pkg/enqueue/Symfony/DependencyInjection/BuildProcessorRegistryPass.php
+++ b/pkg/enqueue/Symfony/DependencyInjection/BuildProcessorRegistryPass.php
@@ -2,6 +2,7 @@
namespace Enqueue\Symfony\DependencyInjection;
+use Enqueue\Symfony\DiUtils;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
@@ -9,44 +10,41 @@
final class BuildProcessorRegistryPass implements CompilerPassInterface
{
- /**
- * @var string
- */
- private $name;
-
- public function __construct(string $transportName)
+ public function process(ContainerBuilder $container): void
{
- if (empty($transportName)) {
- throw new \InvalidArgumentException('The name could not be empty.');
+ if (false == $container->hasParameter('enqueue.transports')) {
+ throw new \LogicException('The "enqueue.transports" parameter must be set.');
}
- $this->name = $transportName;
- }
+ $names = $container->getParameter('enqueue.transports');
+ $defaultName = $container->getParameter('enqueue.default_transport');
- public function process(ContainerBuilder $container): void
- {
- $processorRegistryId = sprintf('enqueue.transport.%s.processor_registry', $this->name);
- if (false == $container->hasDefinition($processorRegistryId)) {
- return;
- }
+ foreach ($names as $name) {
+ $diUtils = DiUtils::create(TransportFactory::MODULE, $name);
- $tag = 'enqueue.transport.processor';
- $map = [];
- foreach ($container->findTaggedServiceIds($tag) as $serviceId => $tagAttributes) {
- foreach ($tagAttributes as $tagAttribute) {
- $transport = $tagAttribute['transport'] ?? 'default';
+ $processorRegistryId = $diUtils->format('processor_registry');
+ if (false == $container->hasDefinition($processorRegistryId)) {
+ throw new \LogicException(sprintf('Service "%s" not found', $processorRegistryId));
+ }
- if ($transport !== $this->name && 'all' !== $transport) {
- continue;
- }
+ $tag = 'enqueue.transport.processor';
+ $map = [];
+ foreach ($container->findTaggedServiceIds($tag) as $serviceId => $tagAttributes) {
+ foreach ($tagAttributes as $tagAttribute) {
+ $transport = $tagAttribute['transport'] ?? $defaultName;
+
+ if ($transport !== $name && 'all' !== $transport) {
+ continue;
+ }
- $processor = $tagAttribute['processor'] ?? $serviceId;
+ $processor = $tagAttribute['processor'] ?? $serviceId;
- $map[$processor] = new Reference($serviceId);
+ $map[$processor] = new Reference($serviceId);
+ }
}
- }
- $registry = $container->getDefinition($processorRegistryId);
- $registry->setArgument(0, ServiceLocatorTagPass::register($container, $map, $processorRegistryId));
+ $registry = $container->getDefinition($processorRegistryId);
+ $registry->setArgument(0, ServiceLocatorTagPass::register($container, $map, $processorRegistryId));
+ }
}
}
diff --git a/pkg/enqueue/Symfony/DependencyInjection/ClientFactory.php b/pkg/enqueue/Symfony/DependencyInjection/ClientFactory.php
deleted file mode 100644
index fd5a36332..000000000
--- a/pkg/enqueue/Symfony/DependencyInjection/ClientFactory.php
+++ /dev/null
@@ -1,194 +0,0 @@
-name = $name;
- }
-
- public function build(ContainerBuilder $container, array $config): void
- {
- $container->register($this->format('context'), Context::class)
- ->setFactory([$this->reference('driver'), 'getContext'])
- ;
-
- $container->register($this->format('driver_factory'), DriverFactory::class)
- ->addArgument($this->reference('config'))
- ->addArgument($this->reference('route_collection'))
- ;
-
- $container->register($this->format('config'), Config::class)
- ->setArguments([
- $config['prefix'],
- $config['app_name'],
- $config['router_topic'],
- $config['router_queue'],
- $config['default_processor_queue'],
- $config['router_processor'],
- // @todo should be driver options.
- $config['transport'],
- ]);
-
- $container->setParameter($this->format('router_processor'), $config['router_processor']);
- $container->setParameter($this->format('router_queue_name'), $config['router_queue']);
- $container->setParameter($this->format('default_queue_name'), $config['default_processor_queue']);
-
- $container->register($this->format('route_collection'), RouteCollection::class)
- ->addArgument([])
- ->setFactory([RouteCollection::class, 'fromArray'])
- ;
-
- $container->register($this->format('producer'), Producer::class)
- ->addArgument($this->reference('driver'))
- ->addArgument($this->reference('rpc_factory'))
- ->addArgument($this->reference('client_extensions'))
- ;
-
- $container->register($this->format('spool_producer'), SpoolProducer::class)
- ->addArgument($this->reference('producer'))
- ;
-
- $container->register($this->format('client_extensions'), ChainExtension::class)
- ->addArgument([])
- ;
-
- $container->register($this->format('rpc_factory'), RpcFactory::class)
- ->addArgument($this->reference('context'))
- ;
-
- $container->register($this->format('router_processor'), RouterProcessor::class)
- ->addArgument($this->reference('driver'))
- ;
-
- $container->register($this->format('processor_registry'), ContainerProcessorRegistry::class);
-
- $container->register($this->format('delegate_processor'), DelegateProcessor::class)
- ->addArgument($this->reference('processor_registry'))
- ;
-
- $container->register($this->format('set_router_properties_extension'), SetRouterPropertiesExtension::class)
- ->addArgument($this->reference('driver'))
- ->addTag('enqueue.consumption_extension', ['priority' => 100, 'client' => $this->name])
- ;
-
- $container->register($this->format('queue_consumer'), QueueConsumer::class)
- ->addArgument($this->reference('context'))
- ->addArgument($this->reference('consumption_extensions'))
- ->addArgument([])
- ->addArgument($this->reference('logger', ContainerInterface::NULL_ON_INVALID_REFERENCE))
- ->addArgument($config['consumption']['receive_timeout'])
- ;
-
- $container->register($this->format('consumption_extensions'), ConsumptionChainExtension::class)
- ->addArgument([])
- ;
-
- $container->register($this->format('flush_spool_producer_extension'), FlushSpoolProducerExtension::class)
- ->addArgument($this->reference('spool_producer'))
- ->addTag('enqueue.consumption.extension', ['priority' => -100, 'client' => $this->name])
- ;
-
- $container->register($this->format('exclusive_command_extension'), ExclusiveCommandExtension::class)
- ->addArgument($this->reference('driver'))
- ->addTag('enqueue.consumption.extension', ['priority' => 100, 'client' => $this->name])
- ;
-
- if ($config['traceable_producer']) {
- $container->register($this->format('traceable_producer'), TraceableProducer::class)
- ->setDecoratedService($this->format('producer'))
- ->addArgument($this->reference('traceable_producer.inner'))
- ;
- }
-
- if ($config['redelivered_delay_time']) {
- $container->register($this->format('delay_redelivered_message_extension'), DelayRedeliveredMessageExtension::class)
- ->addArgument($this->reference('driver'))
- ->addArgument($config['redelivered_delay_time'])
- ->addTag('enqueue.consumption_extension', ['priority' => 10, 'client' => $this->name])
- ;
-
- $container->getDefinition('enqueue.client.default.delay_redelivered_message_extension')
- ->replaceArgument(1, $config['redelivered_delay_time'])
- ;
- }
-
- $locatorId = 'enqueue.locator';
- if ($container->hasDefinition($locatorId)) {
- $locator = $container->getDefinition($locatorId);
- $locator->replaceArgument(0, array_replace($locator->getArgument(0), [
- $this->format('queue_consumer') => $this->reference('queue_consumer'),
- $this->format('driver') => $this->reference('driver'),
- $this->format('delegate_processor') => $this->reference('delegate_processor'),
- $this->format('producer') => $this->reference('producer'),
- ]));
- }
-
- if ('default' === $this->name) {
- $container->setAlias(ProducerInterface::class, $this->format('producer'));
-
- $container->setAlias(SpoolProducer::class, $this->format('spool_producer'));
- }
- }
-
- public function createDriver(ContainerBuilder $container, array $config): string
- {
- $factoryId = sprintf('enqueue.transport.%s.connection_factory', $this->getName());
- $driverId = sprintf('enqueue.client.%s.driver', $this->getName());
- $driverFactoryId = sprintf('enqueue.client.%s.driver_factory', $this->getName());
-
- $container->register($driverId, DriverInterface::class)
- ->setFactory([new Reference($driverFactoryId), 'create'])
- ->addArgument(new Reference($factoryId))
- ->addArgument($config['dsn'])
- ->addArgument($config)
- ;
-
- return $driverId;
- }
-
- public function getName(): string
- {
- return $this->name;
- }
-}
diff --git a/pkg/enqueue/Symfony/DependencyInjection/FormatClientNameTrait.php b/pkg/enqueue/Symfony/DependencyInjection/FormatClientNameTrait.php
deleted file mode 100644
index 7880d126c..000000000
--- a/pkg/enqueue/Symfony/DependencyInjection/FormatClientNameTrait.php
+++ /dev/null
@@ -1,32 +0,0 @@
-format($serviceName), $invalidBehavior);
- }
-
- private function parameter(string $serviceName): string
- {
- $fullName = $this->format($serviceName, false);
-
- return "%$fullName%";
- }
-
- private function format(string $serviceName, $parameter = false): string
- {
- $pattern = 'enqueue.client.%s.'.$serviceName;
-
- $fullName = sprintf($pattern, $this->getName());
-
- return $parameter ? "%$fullName%" : $fullName;
- }
-}
diff --git a/pkg/enqueue/Symfony/DependencyInjection/FormatTransportNameTrait.php b/pkg/enqueue/Symfony/DependencyInjection/FormatTransportNameTrait.php
deleted file mode 100644
index 17a41d0b9..000000000
--- a/pkg/enqueue/Symfony/DependencyInjection/FormatTransportNameTrait.php
+++ /dev/null
@@ -1,17 +0,0 @@
-getName());
-
- return $parameter ? "%$fullName%" : $fullName;
- }
-}
diff --git a/pkg/enqueue/Symfony/DependencyInjection/TransportFactory.php b/pkg/enqueue/Symfony/DependencyInjection/TransportFactory.php
index f70b1cb5d..944b1a30d 100644
--- a/pkg/enqueue/Symfony/DependencyInjection/TransportFactory.php
+++ b/pkg/enqueue/Symfony/DependencyInjection/TransportFactory.php
@@ -12,9 +12,11 @@
use Enqueue\Rpc\RpcClient;
use Enqueue\Rpc\RpcFactory;
use Enqueue\Symfony\ContainerProcessorRegistry;
+use Enqueue\Symfony\DiUtils;
use Interop\Queue\ConnectionFactory;
use Interop\Queue\Context;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
+use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
@@ -24,27 +26,34 @@
*/
final class TransportFactory
{
- use FormatTransportNameTrait;
+ public const MODULE = 'transport';
/**
- * @var string
+ * @var bool
*/
- private $name;
+ private $default;
- public function __construct(string $name)
+ /**
+ * @var DiUtils
+ */
+ private $diUtils;
+
+ public function __construct(string $name, bool $default = false)
{
if (empty($name)) {
throw new \InvalidArgumentException('The name could not be empty.');
}
- $this->name = $name;
+ $this->default = $default;
+ $this->diUtils = DiUtils::create(self::MODULE, $name);
}
- public function addTransportConfiguration(ArrayNodeDefinition $builder): void
+ public static function getConfiguration(string $name = 'transport'): NodeDefinition
{
$knownSchemes = array_keys(Resources::getKnownSchemes());
$availableSchemes = array_keys(Resources::getAvailableSchemes());
+ $builder = new ArrayNodeDefinition($name);
$builder
->info('The transport option could accept a string DSN, an array with DSN key, or null. It accept extra options. To find out what option you can set, look at connection factory constructor docblock.')
->beforeNormalization()
@@ -72,6 +81,7 @@ public function addTransportConfiguration(ArrayNodeDefinition $builder): void
throw new \LogicException(sprintf('The value must be array, null or string. Got "%s"', gettype($v)));
})
->end()
+ ->isRequired()
->ignoreExtraKeys(false)
->children()
->scalarNode('dsn')
@@ -94,42 +104,43 @@ public function addTransportConfiguration(ArrayNodeDefinition $builder): void
->end()
->end()
;
+
+ return $builder;
}
- public function addQueueConsumerConfiguration(ArrayNodeDefinition $builder): void
+ public static function getQueueConsumerConfiguration(string $name = 'consumption'): ArrayNodeDefinition
{
+ $builder = new ArrayNodeDefinition($name);
+
$builder
->addDefaultsIfNotSet()->children()
->integerNode('receive_timeout')
->min(0)
->defaultValue(10000)
- ->info('the time in milliseconds queue consumer waits for a message (100 ms by default)')
+ ->info('the time in milliseconds queue consumer waits for a message (10000 ms by default)')
->end()
;
- }
- public function getName(): string
- {
- return $this->name;
+ return $builder;
}
public function buildConnectionFactory(ContainerBuilder $container, array $config): void
{
- $factoryId = $this->format('connection_factory');
+ $factoryId = $this->diUtils->format('connection_factory');
- $factoryFactoryId = $this->format('connection_factory_factory');
+ $factoryFactoryId = $this->diUtils->format('connection_factory_factory');
$container->register($factoryFactoryId, $config['factory_class'] ?? ConnectionFactoryFactory::class);
$factoryFactoryService = new Reference(
- array_key_exists('factory_service', $config) ? $config['factory_service'] : $factoryFactoryId
+ $config['factory_service'] ?? $factoryFactoryId
);
unset($config['factory_service'], $config['factory_class']);
- if (array_key_exists('connection_factory_class', $config)) {
- $connectionFactoryClass = $config['connection_factory_class'];
- unset($config['connection_factory_class']);
+ $connectionFactoryClass = $config['connection_factory_class'] ?? null;
+ unset($config['connection_factory_class']);
+ if (isset($connectionFactoryClass)) {
$container->register($factoryId, $connectionFactoryClass)
->addArgument($config)
;
@@ -140,83 +151,95 @@ public function buildConnectionFactory(ContainerBuilder $container, array $confi
;
}
- if ('default' === $this->name) {
- $container->setAlias(ConnectionFactory::class, $this->format('connection_factory'));
+ if ($this->default) {
+ $container->setAlias(ConnectionFactory::class, $factoryId);
+
+ if (DiUtils::DEFAULT_CONFIG !== $this->diUtils->getConfigName()) {
+ $container->setAlias($this->diUtils->formatDefault('connection_factory'), $factoryId);
+ }
}
}
public function buildContext(ContainerBuilder $container, array $config): void
{
- $factoryId = $this->format('connection_factory');
+ $factoryId = $this->diUtils->format('connection_factory');
$this->assertServiceExists($container, $factoryId);
- $contextId = $this->format('context');
+ $contextId = $this->diUtils->format('context');
$container->register($contextId, Context::class)
->setFactory([new Reference($factoryId), 'createContext'])
;
- if ('default' === $this->name) {
- $container->setAlias(Context::class, $this->format('context'));
+ $this->addServiceToLocator($container, 'context');
+
+ if ($this->default) {
+ $container->setAlias(Context::class, $contextId);
+
+ if (DiUtils::DEFAULT_CONFIG !== $this->diUtils->getConfigName()) {
+ $container->setAlias($this->diUtils->formatDefault('context'), $contextId);
+ }
}
}
public function buildQueueConsumer(ContainerBuilder $container, array $config): void
{
- $contextId = $this->format('context');
+ $contextId = $this->diUtils->format('context');
$this->assertServiceExists($container, $contextId);
- $container->setParameter($this->format('receive_timeout'), $config['receive_timeout'] ?? 10000);
+ $container->setParameter($this->diUtils->format('receive_timeout'), $config['receive_timeout'] ?? 10000);
- $logExtensionId = $this->format('log_extension');
+ $logExtensionId = $this->diUtils->format('log_extension');
$container->register($logExtensionId, LogExtension::class)
- ->addTag('enqueue.transport.consumption_extension', ['transport' => $this->name, 'priority' => -100])
+ ->addTag('enqueue.transport.consumption_extension', ['transport' => $this->diUtils->getConfigName(), 'priority' => -100])
;
- $container->register($this->format('consumption_extensions'), ChainExtension::class)
+ $container->register($this->diUtils->format('consumption_extensions'), ChainExtension::class)
->addArgument([])
;
- $container->register($this->format('queue_consumer'), QueueConsumer::class)
+ $container->register($this->diUtils->format('queue_consumer'), QueueConsumer::class)
->addArgument(new Reference($contextId))
- ->addArgument(new Reference($this->format('consumption_extensions')))
+ ->addArgument(new Reference($this->diUtils->format('consumption_extensions')))
->addArgument([])
->addArgument(new Reference('logger', ContainerInterface::NULL_ON_INVALID_REFERENCE))
- ->addArgument($this->format('receive_timeout', true))
+ ->addArgument($this->diUtils->parameter('receive_timeout'))
;
- $container->register($this->format('processor_registry'), ContainerProcessorRegistry::class);
+ $container->register($this->diUtils->format('processor_registry'), ContainerProcessorRegistry::class);
- $locatorId = 'enqueue.locator';
- if ($container->hasDefinition($locatorId)) {
- $locator = $container->getDefinition($locatorId);
- $locator->replaceArgument(0, array_replace($locator->getArgument(0), [
- $this->format('queue_consumer') => new Reference($this->format('queue_consumer')),
- $this->format('processor_registry') => new Reference($this->format('processor_registry')),
- ]));
- }
+ $this->addServiceToLocator($container, 'queue_consumer');
+ $this->addServiceToLocator($container, 'processor_registry');
+
+ if ($this->default) {
+ $container->setAlias(QueueConsumerInterface::class, $this->diUtils->format('queue_consumer'));
- if ('default' === $this->name) {
- $container->setAlias(QueueConsumerInterface::class, $this->format('queue_consumer'));
+ if (DiUtils::DEFAULT_CONFIG !== $this->diUtils->getConfigName()) {
+ $container->setAlias($this->diUtils->formatDefault('queue_consumer'), $this->diUtils->format('queue_consumer'));
+ }
}
}
public function buildRpcClient(ContainerBuilder $container, array $config): void
{
- $contextId = $this->format('context');
+ $contextId = $this->diUtils->format('context');
$this->assertServiceExists($container, $contextId);
- $container->register($this->format('rpc_factory'), RpcFactory::class)
+ $container->register($this->diUtils->format('rpc_factory'), RpcFactory::class)
->addArgument(new Reference($contextId))
;
- $container->register($this->format('rpc_client'), RpcClient::class)
+ $container->register($this->diUtils->format('rpc_client'), RpcClient::class)
->addArgument(new Reference($contextId))
- ->addArgument(new Reference($this->format('rpc_factory')))
+ ->addArgument(new Reference($this->diUtils->format('rpc_factory')))
;
- if ('default' === $this->name) {
- $container->setAlias(RpcClient::class, $this->format('rpc_client'));
+ if ($this->default) {
+ $container->setAlias(RpcClient::class, $this->diUtils->format('rpc_client'));
+
+ if (DiUtils::DEFAULT_CONFIG !== $this->diUtils->getConfigName()) {
+ $container->setAlias($this->diUtils->formatDefault('rpc_client'), $this->diUtils->format('rpc_client'));
+ }
}
}
@@ -226,4 +249,18 @@ private function assertServiceExists(ContainerBuilder $container, string $servic
throw new \InvalidArgumentException(sprintf('The service "%s" does not exist.', $serviceId));
}
}
+
+ private function addServiceToLocator(ContainerBuilder $container, string $serviceName): void
+ {
+ $locatorId = 'enqueue.locator';
+
+ if ($container->hasDefinition($locatorId)) {
+ $locator = $container->getDefinition($locatorId);
+
+ $map = $locator->getArgument(0);
+ $map[$this->diUtils->format($serviceName)] = $this->diUtils->reference($serviceName);
+
+ $locator->replaceArgument(0, $map);
+ }
+ }
}
diff --git a/pkg/enqueue/Symfony/DiUtils.php b/pkg/enqueue/Symfony/DiUtils.php
new file mode 100644
index 000000000..be45287be
--- /dev/null
+++ b/pkg/enqueue/Symfony/DiUtils.php
@@ -0,0 +1,81 @@
+moduleName = $moduleName;
+ $this->configName = $configName;
+ }
+
+ public static function create(string $moduleName, string $configName): self
+ {
+ return new self($moduleName, $configName);
+ }
+
+ public function getModuleName(): string
+ {
+ return $this->moduleName;
+ }
+
+ public function getConfigName(): string
+ {
+ return $this->configName;
+ }
+
+ public function reference(string $serviceName, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE): Reference
+ {
+ return new Reference($this->format($serviceName), $invalidBehavior);
+ }
+
+ public function referenceDefault(string $serviceName, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE): Reference
+ {
+ return new Reference($this->formatDefault($serviceName), $invalidBehavior);
+ }
+
+ public function parameter(string $serviceName): string
+ {
+ $fullName = $this->format($serviceName);
+
+ return "%$fullName%";
+ }
+
+ public function parameterDefault(string $serviceName): string
+ {
+ $fullName = $this->formatDefault($serviceName);
+
+ return "%$fullName%";
+ }
+
+ public function format(string $serviceName): string
+ {
+ return $this->doFormat($this->moduleName, $this->configName, $serviceName);
+ }
+
+ public function formatDefault(string $serviceName): string
+ {
+ return $this->doFormat($this->moduleName, self::DEFAULT_CONFIG, $serviceName);
+ }
+
+ private function doFormat(string $moduleName, string $configName, string $serviceName): string
+ {
+ return sprintf('enqueue.%s.%s.%s', $moduleName, $configName, $serviceName);
+ }
+}
diff --git a/pkg/enqueue/Symfony/MissingComponentFactory.php b/pkg/enqueue/Symfony/MissingComponentFactory.php
new file mode 100644
index 000000000..94fcb8339
--- /dev/null
+++ b/pkg/enqueue/Symfony/MissingComponentFactory.php
@@ -0,0 +1,42 @@
+info($message)
+ ->beforeNormalization()
+ ->always(function () {
+ return [];
+ })
+ ->end()
+ ->validate()
+ ->always(function () use ($message) {
+ throw new \InvalidArgumentException($message);
+ })
+ ->end()
+ ;
+
+ return $node;
+ }
+}
diff --git a/pkg/enqueue/Tests/ArrayProcessorRegistryTest.php b/pkg/enqueue/Tests/ArrayProcessorRegistryTest.php
index 50c802582..93ad3ece1 100644
--- a/pkg/enqueue/Tests/ArrayProcessorRegistryTest.php
+++ b/pkg/enqueue/Tests/ArrayProcessorRegistryTest.php
@@ -6,6 +6,7 @@
use Enqueue\ProcessorRegistryInterface;
use Enqueue\Test\ClassExtensionTrait;
use Interop\Queue\Processor;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class ArrayProcessorRegistryTest extends TestCase
@@ -17,11 +18,6 @@ public function testShouldImplementProcessorRegistryInterface()
$this->assertClassImplements(ProcessorRegistryInterface::class, ArrayProcessorRegistry::class);
}
- public function testCouldBeConstructedWithoutAnyArgument()
- {
- new ArrayProcessorRegistry();
- }
-
public function testShouldThrowExceptionIfProcessorIsNotSet()
{
$registry = new ArrayProcessorRegistry();
@@ -51,7 +47,7 @@ public function testShouldAllowGetProcessorAddedViaAddMethod()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Processor
+ * @return MockObject|Processor
*/
protected function createProcessorMock()
{
diff --git a/pkg/enqueue/Tests/Client/ChainExtensionTest.php b/pkg/enqueue/Tests/Client/ChainExtensionTest.php
index a48da5f81..0f42bcf18 100644
--- a/pkg/enqueue/Tests/Client/ChainExtensionTest.php
+++ b/pkg/enqueue/Tests/Client/ChainExtensionTest.php
@@ -11,6 +11,8 @@
use Enqueue\Client\PreSend;
use Enqueue\Client\ProducerInterface;
use Enqueue\Test\ClassExtensionTrait;
+use Interop\Queue\Destination;
+use Interop\Queue\Message as TransportMessage;
use PHPUnit\Framework\TestCase;
class ChainExtensionTest extends TestCase
@@ -27,22 +29,10 @@ public function testShouldBeFinal()
$this->assertClassFinal(ChainExtension::class);
}
- public function testShouldInitEmptyExtensionsArrayOnConstruct()
- {
- $extension = new ChainExtension([]);
-
- $this->assertAttributeSame([], 'extensions', $extension);
- }
-
- public function testCouldBeConstructedWithExtensionsArray()
- {
- new ChainExtension([$this->createExtension(), $this->createExtension()]);
- }
-
public function testThrowIfArrayContainsNotExtension()
{
- $this->expectException(\TypeError::class);
- $this->expectExceptionMessage('Argument 1 passed to');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Invalid extension given');
new ChainExtension([$this->createExtension(), new \stdClass()]);
}
@@ -132,7 +122,9 @@ public function testShouldProxyOnPostSentToAllInternalExtensions()
$postSend = new PostSend(
new Message(),
$this->createMock(ProducerInterface::class),
- $this->createMock(DriverInterface::class)
+ $this->createMock(DriverInterface::class),
+ $this->createMock(Destination::class),
+ $this->createMock(TransportMessage::class)
);
$fooExtension = $this->createExtension();
@@ -154,7 +146,7 @@ public function testShouldProxyOnPostSentToAllInternalExtensions()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ExtensionInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|ExtensionInterface
*/
protected function createExtension()
{
diff --git a/pkg/enqueue/Tests/Client/ConfigTest.php b/pkg/enqueue/Tests/Client/ConfigTest.php
index 8e54508cf..09b80e2c1 100644
--- a/pkg/enqueue/Tests/Client/ConfigTest.php
+++ b/pkg/enqueue/Tests/Client/ConfigTest.php
@@ -11,11 +11,14 @@ public function testShouldReturnPrefixSetInConstructor()
{
$config = new Config(
'thePrefix',
+ 'theSeparator',
'aApp',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueueName',
- 'aRouterProcessorName'
+ 'aRouterProcessorName',
+ [],
+ []
);
$this->assertEquals('thePrefix', $config->getPrefix());
@@ -29,10 +32,13 @@ public function testShouldTrimReturnPrefixSetInConstructor(string $empty)
$config = new Config(
$empty,
'aApp',
+ 'theSeparator',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueueName',
- 'aRouterProcessorName'
+ 'aRouterProcessorName',
+ [],
+ []
);
$this->assertSame('', $config->getPrefix());
@@ -42,11 +48,14 @@ public function testShouldReturnAppNameSetInConstructor()
{
$config = new Config(
'aPrefix',
+ 'theSeparator',
'theApp',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueueName',
- 'aRouterProcessorName'
+ 'aRouterProcessorName',
+ [],
+ []
);
$this->assertEquals('theApp', $config->getApp());
@@ -59,11 +68,14 @@ public function testShouldTrimReturnAppNameSetInConstructor(string $empty)
{
$config = new Config(
'aPrefix',
+ 'theSeparator',
$empty,
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueueName',
- 'aRouterProcessorName'
+ 'aRouterProcessorName',
+ [],
+ []
);
$this->assertSame('', $config->getApp());
@@ -73,11 +85,14 @@ public function testShouldReturnRouterProcessorNameSetInConstructor()
{
$config = new Config(
'aPrefix',
+ 'theSeparator',
'aApp',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueueName',
- 'aRouterProcessorName'
+ 'aRouterProcessorName',
+ [],
+ []
);
$this->assertEquals('aRouterProcessorName', $config->getRouterProcessor());
@@ -87,11 +102,14 @@ public function testShouldReturnRouterTopicNameSetInConstructor()
{
$config = new Config(
'aPrefix',
+ 'theSeparator',
'aApp',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueueName',
- 'aRouterProcessorName'
+ 'aRouterProcessorName',
+ [],
+ []
);
$this->assertEquals('aRouterTopicName', $config->getRouterTopic());
@@ -101,11 +119,14 @@ public function testShouldReturnRouterQueueNameSetInConstructor()
{
$config = new Config(
'aPrefix',
+ 'theSeparator',
'aApp',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueueName',
- 'aRouterProcessorName'
+ 'aRouterProcessorName',
+ [],
+ []
);
$this->assertEquals('aRouterQueueName', $config->getRouterQueue());
@@ -115,11 +136,14 @@ public function testShouldReturnDefaultQueueNameSetInConstructor()
{
$config = new Config(
'aPrefix',
+ 'theSeparator',
'aApp',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueueName',
- 'aRouterProcessorName'
+ 'aRouterProcessorName',
+ [],
+ []
);
$this->assertEquals('aDefaultQueueName', $config->getDefaultQueue());
@@ -143,12 +167,15 @@ public function testThrowIfRouterTopicNameIsEmpty(string $empty)
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Router topic is empty.');
new Config(
+ '',
'',
'',
$empty,
'aRouterQueueName',
'aDefaultQueueName',
- 'aRouterProcessorName'
+ 'aRouterProcessorName',
+ [],
+ []
);
}
@@ -160,12 +187,15 @@ public function testThrowIfRouterQueueNameIsEmpty(string $empty)
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Router queue is empty.');
new Config(
+ '',
'',
'',
'aRouterTopicName',
$empty,
'aDefaultQueueName',
- 'aRouterProcessorName'
+ 'aRouterProcessorName',
+ [],
+ []
);
}
@@ -177,12 +207,15 @@ public function testThrowIfDefaultQueueNameIsEmpty(string $empty)
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Default processor queue name is empty.');
new Config(
+ '',
'',
'',
'aRouterTopicName',
'aRouterQueueName',
$empty,
- 'aRouterProcessorName'
+ 'aRouterProcessorName',
+ [],
+ []
);
}
@@ -194,12 +227,15 @@ public function testThrowIfRouterProcessorNameIsEmpty(string $empty)
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Router processor name is empty.');
new Config(
+ '',
'',
'',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueueName',
- $empty
+ $empty,
+ [],
+ []
);
}
diff --git a/pkg/enqueue/Tests/Client/ConsumptionExtension/DelayRedeliveredMessageExtensionTest.php b/pkg/enqueue/Tests/Client/ConsumptionExtension/DelayRedeliveredMessageExtensionTest.php
index 8b6019ec3..a660126ad 100644
--- a/pkg/enqueue/Tests/Client/ConsumptionExtension/DelayRedeliveredMessageExtensionTest.php
+++ b/pkg/enqueue/Tests/Client/ConsumptionExtension/DelayRedeliveredMessageExtensionTest.php
@@ -4,25 +4,25 @@
use Enqueue\Client\ConsumptionExtension\DelayRedeliveredMessageExtension;
use Enqueue\Client\DriverInterface;
+use Enqueue\Client\DriverSendResult;
use Enqueue\Client\Message;
use Enqueue\Consumption\Context\MessageReceived;
use Enqueue\Consumption\Result;
use Enqueue\Null\NullMessage;
use Enqueue\Null\NullQueue;
+use Enqueue\Test\TestLogger;
use Interop\Queue\Consumer;
use Interop\Queue\Context as InteropContext;
+use Interop\Queue\Destination;
+use Interop\Queue\Message as TransportMessage;
use Interop\Queue\Processor;
+use Interop\Queue\Queue;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
-use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
class DelayRedeliveredMessageExtensionTest extends TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new DelayRedeliveredMessageExtension($this->createDriverMock(), 12345);
- }
-
public function testShouldSendDelayedMessageAndRejectOriginalMessage()
{
$queue = new NullQueue('queue');
@@ -41,6 +41,7 @@ public function testShouldSendDelayedMessageAndRejectOriginalMessage()
->expects(self::once())
->method('sendToProcessor')
->with(self::isInstanceOf(Message::class))
+ ->willReturn($this->createDriverSendResult())
;
$driver
->expects(self::once())
@@ -49,20 +50,7 @@ public function testShouldSendDelayedMessageAndRejectOriginalMessage()
->willReturn($delayedMessage)
;
- $logger = $this->createLoggerMock();
- $logger
- ->expects(self::at(0))
- ->method('debug')
- ->with('[DelayRedeliveredMessageExtension] Send delayed message')
- ;
- $logger
- ->expects(self::at(1))
- ->method('debug')
- ->with(
- '[DelayRedeliveredMessageExtension] '.
- 'Reject redelivered original message by setting reject status to context.'
- )
- ;
+ $logger = new TestLogger();
$messageReceived = new MessageReceived(
$this->createContextMock(),
@@ -87,6 +75,16 @@ public function testShouldSendDelayedMessageAndRejectOriginalMessage()
$this->assertEquals([
'enqueue.redelivery_count' => 1,
], $delayedMessage->getProperties());
+
+ self::assertTrue(
+ $logger->hasDebugThatContains('[DelayRedeliveredMessageExtension] Send delayed message')
+ );
+ self::assertTrue(
+ $logger->hasDebugThatContains(
+ '[DelayRedeliveredMessageExtension] '.
+ 'Reject redelivered original message by setting reject status to context.'
+ )
+ );
}
public function testShouldDoNothingIfMessageIsNotRedelivered()
@@ -140,7 +138,7 @@ public function testShouldDoNothingIfMessageIsRedeliveredButResultWasAlreadySetO
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createDriverMock(): DriverInterface
{
@@ -148,7 +146,7 @@ private function createDriverMock(): DriverInterface
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createContextMock(): InteropContext
{
@@ -156,7 +154,7 @@ private function createContextMock(): InteropContext
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createProcessorMock(): Processor
{
@@ -164,27 +162,25 @@ private function createProcessorMock(): Processor
}
/**
- * @param mixed $queue
- *
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject|Consumer
*/
- private function createConsumerStub($queue): Consumer
+ private function createConsumerStub(?Queue $queue): Consumer
{
$consumerMock = $this->createMock(Consumer::class);
$consumerMock
->expects($this->any())
->method('getQueue')
- ->willReturn($queue)
+ ->willReturn($queue ?? new NullQueue('queue'))
;
return $consumerMock;
}
- /**
- * @return \PHPUnit_Framework_MockObject_MockObject
- */
- private function createLoggerMock(): LoggerInterface
+ private function createDriverSendResult(): DriverSendResult
{
- return $this->createMock(LoggerInterface::class);
+ return new DriverSendResult(
+ $this->createMock(Destination::class),
+ $this->createMock(TransportMessage::class)
+ );
}
}
diff --git a/pkg/enqueue/Tests/Client/ConsumptionExtension/ExclusiveCommandExtensionTest.php b/pkg/enqueue/Tests/Client/ConsumptionExtension/ExclusiveCommandExtensionTest.php
index 3e1ef2ba0..b1e47c898 100644
--- a/pkg/enqueue/Tests/Client/ConsumptionExtension/ExclusiveCommandExtensionTest.php
+++ b/pkg/enqueue/Tests/Client/ConsumptionExtension/ExclusiveCommandExtensionTest.php
@@ -15,6 +15,8 @@
use Interop\Queue\Consumer;
use Interop\Queue\Context as InteropContext;
use Interop\Queue\Processor;
+use Interop\Queue\Queue;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
@@ -32,11 +34,6 @@ public function testShouldBeFinal()
$this->assertClassFinal(ExclusiveCommandExtension::class);
}
- public function testCouldBeConstructedWithDriverAsFirstArgument()
- {
- new ExclusiveCommandExtension($this->createDriverStub());
- }
-
public function testShouldDoNothingIfMessageHasTopicPropertySetOnPreReceive()
{
$message = new NullMessage();
@@ -181,9 +178,10 @@ public function testShouldSetCommandPropertiesIfCurrentQueueHasExclusiveCommandP
$driver = $this->createDriverStub($routeCollection);
$driver
->expects($this->any())
- ->method('createQueue')
- ->willReturnCallback(function (string $queueName) {
- return new NullQueue($queueName);
+ ->method('createRouteQueue')
+ ->with($this->isInstanceOf(Route::class))
+ ->willReturnCallback(function (Route $route) {
+ return new NullQueue($route->getQueue());
})
;
@@ -241,22 +239,22 @@ public function testShouldDoNothingIfAnotherQueue()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject|DriverInterface
*/
- private function createDriverStub(RouteCollection $routeCollection = null): DriverInterface
+ private function createDriverStub(?RouteCollection $routeCollection = null): DriverInterface
{
$driver = $this->createMock(DriverInterface::class);
$driver
->expects($this->any())
->method('getRouteCollection')
- ->willReturn($routeCollection)
+ ->willReturn($routeCollection ?? new RouteCollection([]))
;
return $driver;
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createContextMock(): InteropContext
{
@@ -264,7 +262,7 @@ private function createContextMock(): InteropContext
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createProcessorMock(): Processor
{
@@ -272,17 +270,15 @@ private function createProcessorMock(): Processor
}
/**
- * @param mixed $queue
- *
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject|Consumer
*/
- private function createConsumerStub($queue): Consumer
+ private function createConsumerStub(?Queue $queue): Consumer
{
$consumerMock = $this->createMock(Consumer::class);
$consumerMock
->expects($this->any())
->method('getQueue')
- ->willReturn($queue)
+ ->willReturn($queue ?? new NullQueue('queue'))
;
return $consumerMock;
diff --git a/pkg/enqueue/Tests/Client/ConsumptionExtension/FlushSpoolProducerExtensionTest.php b/pkg/enqueue/Tests/Client/ConsumptionExtension/FlushSpoolProducerExtensionTest.php
index 53d88aa8d..6a782c524 100644
--- a/pkg/enqueue/Tests/Client/ConsumptionExtension/FlushSpoolProducerExtensionTest.php
+++ b/pkg/enqueue/Tests/Client/ConsumptionExtension/FlushSpoolProducerExtensionTest.php
@@ -12,6 +12,7 @@
use Interop\Queue\Consumer;
use Interop\Queue\Context;
use Interop\Queue\Message;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
@@ -29,11 +30,6 @@ public function testShouldImplementEndExtensionInterface()
$this->assertClassImplements(EndExtensionInterface::class, FlushSpoolProducerExtension::class);
}
- public function testCouldBeConstructedWithSpoolProducerAsFirstArgument()
- {
- new FlushSpoolProducerExtension($this->createSpoolProducerMock());
- }
-
public function testShouldFlushSpoolProducerOnEnd()
{
$producer = $this->createSpoolProducerMock();
@@ -70,7 +66,7 @@ public function testShouldFlushSpoolProducerOnPostReceived()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createInteropContextMock(): Context
{
@@ -78,7 +74,7 @@ private function createInteropContextMock(): Context
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|SpoolProducer
+ * @return MockObject|SpoolProducer
*/
private function createSpoolProducerMock()
{
diff --git a/pkg/enqueue/Tests/Client/ConsumptionExtension/LogExtensionTest.php b/pkg/enqueue/Tests/Client/ConsumptionExtension/LogExtensionTest.php
index 0bd6514d8..383ec4d9b 100644
--- a/pkg/enqueue/Tests/Client/ConsumptionExtension/LogExtensionTest.php
+++ b/pkg/enqueue/Tests/Client/ConsumptionExtension/LogExtensionTest.php
@@ -21,6 +21,7 @@
use Interop\Queue\Context;
use Interop\Queue\Processor;
use Interop\Queue\Queue;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
@@ -54,11 +55,6 @@ public function testShouldSubClassOfLogExtension()
$this->assertClassExtends(\Enqueue\Consumption\Extension\LogExtension::class, LogExtension::class);
}
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new LogExtension();
- }
-
public function testShouldLogStartOnStart()
{
$logger = $this->createLogger();
@@ -95,7 +91,7 @@ public function testShouldLogMessageReceived()
$logger
->expects($this->once())
->method('debug')
- ->with('Received from {queueName} {body}', [
+ ->with('Received from {queueName}', [
'queueName' => 'aQueue',
'redelivered' => false,
'body' => Stringify::that('aBody'),
@@ -122,7 +118,7 @@ public function testShouldLogMessageProcessedWithStringResult()
->expects($this->once())
->method('log')
->with(LogLevel::INFO,
- 'Processed from {queueName} {body} {result}',
+ 'Processed from {queueName}',
[
'queueName' => 'aQueue',
'body' => Stringify::that('aBody'),
@@ -152,7 +148,7 @@ public function testShouldLogRejectedMessageAsError()
->expects($this->once())
->method('log')
->with(LogLevel::ERROR,
- 'Processed from {queueName} {body} {result}',
+ 'Processed from {queueName}',
[
'queueName' => 'aQueue',
'body' => Stringify::that('aBody'),
@@ -182,7 +178,7 @@ public function testShouldLogMessageProcessedWithResultObject()
->expects($this->once())
->method('log')
->with(LogLevel::INFO,
- 'Processed from {queueName} {body} {result}',
+ 'Processed from {queueName}',
[
'queueName' => 'aQueue',
'body' => Stringify::that('aBody'),
@@ -212,7 +208,7 @@ public function testShouldLogMessageProcessedWithReasonResultObject()
->expects($this->once())
->method('log')
->with(LogLevel::INFO,
- 'Processed from {queueName} {body} {result} {reason}',
+ 'Processed from {queueName}',
[
'queueName' => 'aQueue',
'body' => Stringify::that('aBody'),
@@ -500,7 +496,7 @@ public function testShouldLogProcessedTopicProcessorMessageWithReasonResultObjec
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createConsumerStub(Queue $queue): Consumer
{
@@ -515,7 +511,7 @@ private function createConsumerStub(Queue $queue): Consumer
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createContextMock(): Context
{
@@ -523,7 +519,7 @@ private function createContextMock(): Context
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createProcessorMock(): Processor
{
@@ -531,7 +527,7 @@ private function createProcessorMock(): Processor
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|LoggerInterface
+ * @return MockObject|LoggerInterface
*/
private function createLogger()
{
diff --git a/pkg/enqueue/Tests/Client/ConsumptionExtension/SetRouterPropertiesExtensionTest.php b/pkg/enqueue/Tests/Client/ConsumptionExtension/SetRouterPropertiesExtensionTest.php
index be5609db6..d521aefca 100644
--- a/pkg/enqueue/Tests/Client/ConsumptionExtension/SetRouterPropertiesExtensionTest.php
+++ b/pkg/enqueue/Tests/Client/ConsumptionExtension/SetRouterPropertiesExtensionTest.php
@@ -13,6 +13,8 @@
use Interop\Queue\Consumer;
use Interop\Queue\Context as InteropContext;
use Interop\Queue\Processor;
+use Interop\Queue\Queue;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
@@ -25,14 +27,9 @@ public function testShouldImplementMessageReceivedExtensionInterface()
$this->assertClassImplements(MessageReceivedExtensionInterface::class, SetRouterPropertiesExtension::class);
}
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new SetRouterPropertiesExtension($this->createDriverMock());
- }
-
public function testShouldSetRouterProcessorPropertyIfNotSetAndOnRouterQueue()
{
- $config = Config::create('test', '', '', 'router-queue', '', 'router-processor-name');
+ $config = Config::create('test', '.', '', '', 'router-queue', '', 'router-processor-name');
$queue = new NullQueue('test.router-queue');
$driver = $this->createDriverMock();
@@ -49,6 +46,7 @@ public function testShouldSetRouterProcessorPropertyIfNotSetAndOnRouterQueue()
;
$message = new NullMessage();
+ $message->setProperty(Config::TOPIC, 'aTopic');
$messageReceived = new MessageReceived(
$this->createContextMock(),
@@ -64,6 +62,7 @@ public function testShouldSetRouterProcessorPropertyIfNotSetAndOnRouterQueue()
$this->assertEquals([
Config::PROCESSOR => 'router-processor-name',
+ Config::TOPIC => 'aTopic',
], $message->getProperties());
}
@@ -86,6 +85,7 @@ public function testShouldNotSetRouterProcessorPropertyIfNotSetAndNotOnRouterQue
;
$message = new NullMessage();
+ $message->setProperty(Config::TOPIC, 'aTopic');
$messageReceived = new MessageReceived(
$this->createContextMock(),
@@ -99,7 +99,9 @@ public function testShouldNotSetRouterProcessorPropertyIfNotSetAndNotOnRouterQue
$extension = new SetRouterPropertiesExtension($driver);
$extension->onMessageReceived($messageReceived);
- $this->assertEquals([], $message->getProperties());
+ $this->assertEquals([
+ Config::TOPIC => 'aTopic',
+ ], $message->getProperties());
}
public function testShouldNotSetAnyPropertyIfProcessorNamePropertyAlreadySet()
@@ -130,8 +132,33 @@ public function testShouldNotSetAnyPropertyIfProcessorNamePropertyAlreadySet()
], $message->getProperties());
}
+ public function testShouldSkipMessagesWithoutTopicPropertySet()
+ {
+ $driver = $this->createDriverMock();
+ $driver
+ ->expects($this->never())
+ ->method('getConfig')
+ ;
+
+ $message = new NullMessage();
+
+ $messageReceived = new MessageReceived(
+ $this->createContextMock(),
+ $this->createConsumerStub(null),
+ $message,
+ $this->createProcessorMock(),
+ 1,
+ new NullLogger()
+ );
+
+ $extension = new SetRouterPropertiesExtension($driver);
+ $extension->onMessageReceived($messageReceived);
+
+ $this->assertEquals([], $message->getProperties());
+ }
+
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|InteropContext
+ * @return MockObject|InteropContext
*/
protected function createContextMock(): InteropContext
{
@@ -139,7 +166,7 @@ protected function createContextMock(): InteropContext
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|DriverInterface
+ * @return MockObject|DriverInterface
*/
protected function createDriverMock(): DriverInterface
{
@@ -147,7 +174,7 @@ protected function createDriverMock(): DriverInterface
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createProcessorMock(): Processor
{
@@ -155,17 +182,15 @@ private function createProcessorMock(): Processor
}
/**
- * @param mixed $queue
- *
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject|Consumer
*/
- private function createConsumerStub($queue): Consumer
+ private function createConsumerStub(?Queue $queue): Consumer
{
$consumerMock = $this->createMock(Consumer::class);
$consumerMock
->expects($this->any())
->method('getQueue')
- ->willReturn($queue)
+ ->willReturn($queue ?? new NullQueue('queue'))
;
return $consumerMock;
diff --git a/pkg/enqueue/Tests/Client/ConsumptionExtension/SetupBrokerExtensionTest.php b/pkg/enqueue/Tests/Client/ConsumptionExtension/SetupBrokerExtensionTest.php
index 014c23289..fbd367975 100644
--- a/pkg/enqueue/Tests/Client/ConsumptionExtension/SetupBrokerExtensionTest.php
+++ b/pkg/enqueue/Tests/Client/ConsumptionExtension/SetupBrokerExtensionTest.php
@@ -8,6 +8,7 @@
use Enqueue\Consumption\StartExtensionInterface;
use Enqueue\Test\ClassExtensionTrait;
use Interop\Queue\Context as InteropContext;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
@@ -20,11 +21,6 @@ public function testShouldImplementStartExtensionInterface()
$this->assertClassImplements(StartExtensionInterface::class, SetupBrokerExtension::class);
}
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new SetupBrokerExtension($this->createDriverMock());
- }
-
public function testShouldSetupBroker()
{
$logger = new NullLogger();
@@ -61,7 +57,7 @@ public function testShouldSetupBrokerOnlyOnce()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|DriverInterface
+ * @return MockObject|DriverInterface
*/
private function createDriverMock()
{
diff --git a/pkg/enqueue/Tests/Client/DelegateProcessorTest.php b/pkg/enqueue/Tests/Client/DelegateProcessorTest.php
index 5ed49d8bc..9743cf4f3 100644
--- a/pkg/enqueue/Tests/Client/DelegateProcessorTest.php
+++ b/pkg/enqueue/Tests/Client/DelegateProcessorTest.php
@@ -8,15 +8,11 @@
use Enqueue\ProcessorRegistryInterface;
use Interop\Queue\Context;
use Interop\Queue\Processor;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class DelegateProcessorTest extends TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new DelegateProcessor($this->createProcessorRegistryMock());
- }
-
public function testShouldThrowExceptionIfProcessorNameIsNotSet()
{
$this->expectException(\LogicException::class);
@@ -39,7 +35,7 @@ public function testShouldProcessMessage()
->expects($this->once())
->method('process')
->with($this->identicalTo($message), $this->identicalTo($session))
- ->will($this->returnValue('return-value'))
+ ->willReturn('return-value')
;
$processorRegistry = $this->createProcessorRegistryMock();
@@ -47,7 +43,7 @@ public function testShouldProcessMessage()
->expects($this->once())
->method('get')
->with('processor-name')
- ->will($this->returnValue($processor))
+ ->willReturn($processor)
;
$processor = new DelegateProcessor($processorRegistry);
@@ -57,7 +53,7 @@ public function testShouldProcessMessage()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ProcessorRegistryInterface
+ * @return MockObject|ProcessorRegistryInterface
*/
protected function createProcessorRegistryMock()
{
@@ -65,7 +61,7 @@ protected function createProcessorRegistryMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Context
+ * @return MockObject|Context
*/
protected function createContextMock()
{
@@ -73,7 +69,7 @@ protected function createContextMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Processor
+ * @return MockObject|Processor
*/
protected function createProcessorMock()
{
diff --git a/pkg/enqueue/Tests/Client/Driver/AmqpDriverTest.php b/pkg/enqueue/Tests/Client/Driver/AmqpDriverTest.php
index 4e4cc62fd..2cfb170b9 100644
--- a/pkg/enqueue/Tests/Client/Driver/AmqpDriverTest.php
+++ b/pkg/enqueue/Tests/Client/Driver/AmqpDriverTest.php
@@ -2,6 +2,7 @@
namespace Enqueue\Tests\Client\Driver;
+use DMS\PHPUnitExtensions\ArraySubset\Assert;
use Enqueue\Client\Config;
use Enqueue\Client\Driver\AmqpDriver;
use Enqueue\Client\Driver\GenericDriver;
@@ -312,9 +313,6 @@ protected function createQueue(string $name): InteropQueue
return new AmqpQueue($name);
}
- /**
- * @return AmqpTopic
- */
protected function createTopic(string $name): AmqpTopic
{
return new AmqpTopic($name);
@@ -336,7 +334,7 @@ protected function getRouterTransportName(): string
protected function assertTransportMessage(InteropMessage $transportMessage): void
{
$this->assertSame('body', $transportMessage->getBody());
- $this->assertArraySubset([
+ Assert::assertArraySubset([
'hkey' => 'hval',
'delivery_mode' => AmqpMessage::DELIVERY_MODE_PERSISTENT,
'content_type' => 'ContentType',
diff --git a/pkg/enqueue/Tests/Client/Driver/GenericDriverTest.php b/pkg/enqueue/Tests/Client/Driver/GenericDriverTest.php
index 98b6c2285..78f7f6e83 100644
--- a/pkg/enqueue/Tests/Client/Driver/GenericDriverTest.php
+++ b/pkg/enqueue/Tests/Client/Driver/GenericDriverTest.php
@@ -2,6 +2,7 @@
namespace Enqueue\Tests\Client\Driver;
+use DMS\PHPUnitExtensions\ArraySubset\Assert;
use Enqueue\Client\Config;
use Enqueue\Client\Driver\GenericDriver;
use Enqueue\Client\DriverInterface;
@@ -60,7 +61,7 @@ protected function createMessage(): InteropMessage
protected function assertTransportMessage(InteropMessage $transportMessage): void
{
$this->assertSame('body', $transportMessage->getBody());
- $this->assertArraySubset([
+ Assert::assertArraySubset([
'hkey' => 'hval',
'message_id' => 'theMessageId',
'timestamp' => 1000,
diff --git a/pkg/enqueue/Tests/Client/Driver/GenericDriverTestsTrait.php b/pkg/enqueue/Tests/Client/Driver/GenericDriverTestsTrait.php
index 2d39018fa..d5ad498a9 100644
--- a/pkg/enqueue/Tests/Client/Driver/GenericDriverTestsTrait.php
+++ b/pkg/enqueue/Tests/Client/Driver/GenericDriverTestsTrait.php
@@ -2,6 +2,7 @@
namespace Enqueue\Tests\Client\Driver;
+use DMS\PHPUnitExtensions\ArraySubset\Assert;
use Enqueue\Client\Config;
use Enqueue\Client\DriverInterface;
use Enqueue\Client\Message;
@@ -70,11 +71,13 @@ public function testShouldCreateAndReturnQueueInstanceWithPrefixAndAppName()
$config = new Config(
'aPrefix',
+ '.',
'anAppName',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueue',
'aRouterProcessor',
+ [],
[]
);
@@ -99,11 +102,13 @@ public function testShouldCreateAndReturnQueueInstanceWithPrefixWithoutAppName()
$config = new Config(
'aPrefix',
+ '.',
'',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueue',
'aRouterProcessor',
+ [],
[]
);
@@ -128,11 +133,13 @@ public function testShouldCreateAndReturnQueueInstanceWithAppNameAndWithoutPrefi
$config = new Config(
'',
+ '.',
'anAppName',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueue',
'aRouterProcessor',
+ [],
[]
);
@@ -157,11 +164,13 @@ public function testShouldCreateAndReturnQueueInstanceWithoutPrefixAndAppName()
$config = new Config(
'',
+ '.',
'',
'aRouterTopicName',
'aRouterQueueName',
'aDefaultQueue',
'aRouterProcessor',
+ [],
[]
);
@@ -437,6 +446,54 @@ public function testThrowIfCommandSetOnSendToRouter()
$driver->sendToRouter($message);
}
+ public function testShouldSendMessageToRouterProcessor()
+ {
+ $queue = $this->createQueue('');
+ $transportMessage = $this->createMessage();
+
+ $producer = $this->createProducerMock();
+ $producer
+ ->expects($this->once())
+ ->method('send')
+ ->with($this->identicalTo($queue), $this->identicalTo($transportMessage))
+ ;
+ $context = $this->createContextMock();
+ $context
+ ->expects($this->once())
+ ->method('createQueue')
+ ->with($this->getDefaultQueueTransportName())
+ ->willReturn($queue)
+ ;
+ $context
+ ->expects($this->once())
+ ->method('createProducer')
+ ->willReturn($producer)
+ ;
+ $context
+ ->expects($this->once())
+ ->method('createMessage')
+ ->willReturn($transportMessage)
+ ;
+
+ $config = $this->createDummyConfig();
+
+ $driver = $this->createDriver(
+ $context,
+ $config,
+ new RouteCollection([
+ new Route('topic', Route::TOPIC, 'processor', [
+ 'queue' => 'custom',
+ ]),
+ ])
+ );
+
+ $message = new Message();
+ $message->setProperty(Config::TOPIC, 'topic');
+ $message->setProperty(Config::PROCESSOR, $config->getRouterProcessor());
+
+ $driver->sendToProcessor($message);
+ }
+
public function testShouldSendTopicMessageToProcessorToDefaultQueue()
{
$queue = $this->createQueue('');
@@ -1068,12 +1125,12 @@ public function testThrowIfNeitherTopicNorCommandAreSentOnSendToProcessor()
abstract protected function createDriver(...$args): DriverInterface;
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
abstract protected function createContextMock(): Context;
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
abstract protected function createProducerMock(): InteropProducer;
@@ -1084,7 +1141,7 @@ abstract protected function createTopic(string $name): InteropTopic;
abstract protected function createMessage(): InteropMessage;
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
protected function createContextStub(): Context
{
@@ -1135,10 +1192,10 @@ protected function assertTransportMessage(InteropMessage $transportMessage): voi
protected function assertClientMessage(Message $clientMessage): void
{
$this->assertSame('body', $clientMessage->getBody());
- $this->assertArraySubset([
+ Assert::assertArraySubset([
'hkey' => 'hval',
], $clientMessage->getHeaders());
- $this->assertArraySubset([
+ Assert::assertArraySubset([
'pkey' => 'pval',
Config::CONTENT_TYPE => 'theContentType',
Config::EXPIRE => '22',
diff --git a/pkg/enqueue/Tests/Client/Driver/RabbitMqDriverTest.php b/pkg/enqueue/Tests/Client/Driver/RabbitMqDriverTest.php
index 2f6e20a82..b209d85bc 100644
--- a/pkg/enqueue/Tests/Client/Driver/RabbitMqDriverTest.php
+++ b/pkg/enqueue/Tests/Client/Driver/RabbitMqDriverTest.php
@@ -2,6 +2,7 @@
namespace Enqueue\Tests\Client\Driver;
+use DMS\PHPUnitExtensions\ArraySubset\Assert;
use Enqueue\Client\Config;
use Enqueue\Client\Driver\AmqpDriver;
use Enqueue\Client\Driver\GenericDriver;
@@ -91,9 +92,6 @@ protected function createQueue(string $name): InteropQueue
return new AmqpQueue($name);
}
- /**
- * @return AmqpTopic
- */
protected function createTopic(string $name): AmqpTopic
{
return new AmqpTopic($name);
@@ -115,7 +113,7 @@ protected function getRouterTransportName(): string
protected function assertTransportMessage(InteropMessage $transportMessage): void
{
$this->assertSame('body', $transportMessage->getBody());
- $this->assertArraySubset([
+ Assert::assertArraySubset([
'hkey' => 'hval',
'delivery_mode' => AmqpMessage::DELIVERY_MODE_PERSISTENT,
'content_type' => 'ContentType',
diff --git a/pkg/enqueue/Tests/Client/Driver/RabbitMqStompDriverTest.php b/pkg/enqueue/Tests/Client/Driver/RabbitMqStompDriverTest.php
index 5e6dc245e..9fc72be1e 100644
--- a/pkg/enqueue/Tests/Client/Driver/RabbitMqStompDriverTest.php
+++ b/pkg/enqueue/Tests/Client/Driver/RabbitMqStompDriverTest.php
@@ -12,18 +12,19 @@
use Enqueue\Client\MessagePriority;
use Enqueue\Client\Route;
use Enqueue\Client\RouteCollection;
+use Enqueue\Stomp\ExtensionType;
use Enqueue\Stomp\StompContext;
use Enqueue\Stomp\StompDestination;
use Enqueue\Stomp\StompMessage;
use Enqueue\Stomp\StompProducer;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\TestLogger;
use Interop\Queue\Context;
use Interop\Queue\Message as InteropMessage;
use Interop\Queue\Producer as InteropProducer;
use Interop\Queue\Queue as InteropQueue;
use Interop\Queue\Topic as InteropTopic;
use PHPUnit\Framework\TestCase;
-use Psr\Log\LoggerInterface;
class RabbitMqStompDriverTest extends TestCase
{
@@ -47,7 +48,7 @@ public function testShouldBeSubClassOfStompDriver()
public function testShouldCreateAndReturnStompQueueInstance()
{
- $expectedQueue = new StompDestination();
+ $expectedQueue = new StompDestination(ExtensionType::RABBITMQ);
$context = $this->createContextMock();
$context
@@ -121,6 +122,7 @@ public function testThrowIfDelayIsSetButDelayPluginInstalledOptionIsFalse()
$config = Config::create(
'aPrefix',
+ '.',
'',
null,
null,
@@ -156,6 +158,7 @@ public function testShouldSetXDelayHeaderIfDelayPluginInstalledOptionIsTrue()
$config = Config::create(
'aPrefix',
+ '.',
'',
null,
null,
@@ -183,10 +186,10 @@ public function testShouldInitDeliveryDelayIfDelayPropertyOnSendToProcessor()
public function shouldSendMessageToDelayExchangeIfDelaySet()
{
- $queue = new StompDestination();
+ $queue = new StompDestination(ExtensionType::RABBITMQ);
$queue->setStompName('queueName');
- $delayTopic = new StompDestination();
+ $delayTopic = new StompDestination(ExtensionType::RABBITMQ);
$delayTopic->setStompName('delayTopic');
$transportMessage = new StompMessage();
@@ -232,6 +235,7 @@ public function shouldSendMessageToDelayExchangeIfDelaySet()
$config = Config::create(
'aPrefix',
+ '.',
'',
null,
null,
@@ -261,6 +265,7 @@ public function testShouldNotSetupBrokerIfManagementPluginInstalledOptionIsNotEn
{
$config = Config::create(
'aPrefix',
+ '.',
'',
null,
null,
@@ -276,14 +281,15 @@ public function testShouldNotSetupBrokerIfManagementPluginInstalledOptionIsNotEn
$this->createManagementClientMock()
);
- $logger = $this->createLoggerMock();
- $logger
- ->expects($this->once())
- ->method('debug')
- ->with('[RabbitMqStompDriver] Could not setup broker. The option `management_plugin_installed` is not enabled. Please enable that option and install rabbit management plugin')
- ;
+ $logger = new TestLogger();
$driver->setupBroker($logger);
+
+ self::assertTrue(
+ $logger->hasDebugThatContains(
+ '[RabbitMqStompDriver] Could not setup broker. The option `management_plugin_installed` is not enabled. Please enable that option and install rabbit management plugin'
+ )
+ );
}
public function testShouldSetupBroker()
@@ -335,7 +341,7 @@ public function testShouldSetupBroker()
->expects($this->any())
->method('createQueue')
->willReturnCallback(function (string $name) {
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_QUEUE);
$destination->setStompName($name);
@@ -345,6 +351,7 @@ public function testShouldSetupBroker()
$config = Config::create(
'aPrefix',
+ '.',
'',
null,
null,
@@ -360,29 +367,30 @@ public function testShouldSetupBroker()
$managementClient
);
- $logger = $this->createLoggerMock();
- $logger
- ->expects($this->at(0))
- ->method('debug')
- ->with('[RabbitMqStompDriver] Declare router exchange: aprefix.router')
- ;
- $logger
- ->expects($this->at(1))
- ->method('debug')
- ->with('[RabbitMqStompDriver] Declare router queue: aprefix.default')
- ;
- $logger
- ->expects($this->at(2))
- ->method('debug')
- ->with('[RabbitMqStompDriver] Bind router queue to exchange: aprefix.default -> aprefix.router')
- ;
- $logger
- ->expects($this->at(3))
- ->method('debug')
- ->with('[RabbitMqStompDriver] Declare processor queue: aprefix.default')
- ;
+ $logger = new TestLogger();
$driver->setupBroker($logger);
+
+ self::assertTrue(
+ $logger->hasDebugThatContains(
+ '[RabbitMqStompDriver] Declare router exchange: aprefix.router'
+ )
+ );
+ self::assertTrue(
+ $logger->hasDebugThatContains(
+ '[RabbitMqStompDriver] Declare router queue: aprefix.default'
+ )
+ );
+ self::assertTrue(
+ $logger->hasDebugThatContains(
+ '[RabbitMqStompDriver] Bind router queue to exchange: aprefix.default -> aprefix.router'
+ )
+ );
+ self::assertTrue(
+ $logger->hasDebugThatContains(
+ '[RabbitMqStompDriver] Declare processor queue: aprefix.default'
+ )
+ );
}
public function testSetupBrokerShouldCreateDelayExchangeIfEnabled()
@@ -412,6 +420,7 @@ public function testSetupBrokerShouldCreateDelayExchangeIfEnabled()
$config = Config::create(
'aPrefix',
+ '.',
'',
null,
null,
@@ -425,7 +434,7 @@ public function testSetupBrokerShouldCreateDelayExchangeIfEnabled()
->expects($this->any())
->method('createQueue')
->willReturnCallback(function (string $name) {
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_QUEUE);
$destination->setStompName($name);
@@ -436,7 +445,7 @@ public function testSetupBrokerShouldCreateDelayExchangeIfEnabled()
->expects($this->any())
->method('createTopic')
->willReturnCallback(function (string $name) {
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_TOPIC);
$destination->setStompName($name);
@@ -451,19 +460,20 @@ public function testSetupBrokerShouldCreateDelayExchangeIfEnabled()
$managementClient
);
- $logger = $this->createLoggerMock();
- $logger
- ->expects($this->at(4))
- ->method('debug')
- ->with('[RabbitMqStompDriver] Declare delay exchange: aprefix.default.delayed')
- ;
- $logger
- ->expects($this->at(5))
- ->method('debug')
- ->with('[RabbitMqStompDriver] Bind processor queue to delay exchange: aprefix.default -> aprefix.default.delayed')
- ;
+ $logger = new TestLogger();
$driver->setupBroker($logger);
+
+ self::assertTrue(
+ $logger->hasDebugThatContains(
+ '[RabbitMqStompDriver] Declare delay exchange: aprefix.default.delayed'
+ )
+ );
+ self::assertTrue(
+ $logger->hasDebugThatContains(
+ '[RabbitMqStompDriver] Bind processor queue to delay exchange: aprefix.default -> aprefix.default.delayed'
+ )
+ );
}
protected function createDriver(...$args): DriverInterface
@@ -497,7 +507,7 @@ protected function createProducerMock(): InteropProducer
*/
protected function createQueue(string $name): InteropQueue
{
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_QUEUE);
$destination->setStompName($name);
@@ -509,7 +519,7 @@ protected function createQueue(string $name): InteropQueue
*/
protected function createTopic(string $name): InteropTopic
{
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_TOPIC);
$destination->setStompName($name);
@@ -555,6 +565,7 @@ protected function createDummyConfig(): Config
{
return Config::create(
'aPrefix',
+ '.',
'',
null,
null,
@@ -570,18 +581,10 @@ protected function getRouterTransportName(): string
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createManagementClientMock(): StompManagementClient
{
return $this->createMock(StompManagementClient::class);
}
-
- /**
- * @return \PHPUnit_Framework_MockObject_MockObject|LoggerInterface
- */
- private function createLoggerMock()
- {
- return $this->createMock(LoggerInterface::class);
- }
}
diff --git a/pkg/enqueue/Tests/Client/Driver/RdKafkaDriverTest.php b/pkg/enqueue/Tests/Client/Driver/RdKafkaDriverTest.php
index 659590ba3..c5e40e71d 100644
--- a/pkg/enqueue/Tests/Client/Driver/RdKafkaDriverTest.php
+++ b/pkg/enqueue/Tests/Client/Driver/RdKafkaDriverTest.php
@@ -19,9 +19,6 @@
use Interop\Queue\Queue as InteropQueue;
use PHPUnit\Framework\TestCase;
-/**
- * @group rdkafka
- */
class RdKafkaDriverTest extends TestCase
{
use ClassExtensionTrait;
@@ -102,9 +99,6 @@ protected function createQueue(string $name): InteropQueue
return new RdKafkaTopic($name);
}
- /**
- * @return RdKafkaTopic
- */
protected function createTopic(string $name): RdKafkaTopic
{
return new RdKafkaTopic($name);
diff --git a/pkg/enqueue/Tests/Client/Driver/StompDriverTest.php b/pkg/enqueue/Tests/Client/Driver/StompDriverTest.php
index 67764f3bb..8f777fdbd 100644
--- a/pkg/enqueue/Tests/Client/Driver/StompDriverTest.php
+++ b/pkg/enqueue/Tests/Client/Driver/StompDriverTest.php
@@ -9,6 +9,7 @@
use Enqueue\Client\Message;
use Enqueue\Client\MessagePriority;
use Enqueue\Client\RouteCollection;
+use Enqueue\Stomp\ExtensionType;
use Enqueue\Stomp\StompContext;
use Enqueue\Stomp\StompDestination;
use Enqueue\Stomp\StompMessage;
@@ -127,7 +128,7 @@ protected function createProducerMock(): InteropProducer
*/
protected function createQueue(string $name): InteropQueue
{
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_QUEUE);
$destination->setStompName($name);
@@ -139,7 +140,7 @@ protected function createQueue(string $name): InteropQueue
*/
protected function createTopic(string $name): InteropTopic
{
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_TOPIC);
$destination->setStompName($name);
diff --git a/pkg/enqueue/Tests/Client/Driver/StompManagementClientTest.php b/pkg/enqueue/Tests/Client/Driver/StompManagementClientTest.php
index 325fe2c65..081a62c5f 100644
--- a/pkg/enqueue/Tests/Client/Driver/StompManagementClientTest.php
+++ b/pkg/enqueue/Tests/Client/Driver/StompManagementClientTest.php
@@ -81,7 +81,7 @@ public function testCouldCreateNewInstanceUsingFactory()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Client
+ * @return \PHPUnit\Framework\MockObject\MockObject|Client
*/
private function createClientMock()
{
@@ -89,7 +89,7 @@ private function createClientMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Exchange
+ * @return \PHPUnit\Framework\MockObject\MockObject|Exchange
*/
private function createExchangeMock()
{
@@ -97,7 +97,7 @@ private function createExchangeMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Queue
+ * @return \PHPUnit\Framework\MockObject\MockObject|Queue
*/
private function createQueueMock()
{
@@ -105,7 +105,7 @@ private function createQueueMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Binding
+ * @return \PHPUnit\Framework\MockObject\MockObject|Binding
*/
private function createBindingMock()
{
diff --git a/pkg/enqueue/Tests/Client/DriverFactoryTest.php b/pkg/enqueue/Tests/Client/DriverFactoryTest.php
index c4f1ffb46..3d9d7b9b5 100644
--- a/pkg/enqueue/Tests/Client/DriverFactoryTest.php
+++ b/pkg/enqueue/Tests/Client/DriverFactoryTest.php
@@ -61,11 +61,6 @@ public function testShouldBeFinal()
$this->assertTrue($rc->isFinal());
}
- public function testCouldBeConstructedWithConfigAndRouteCollectionAsArguments()
- {
- new DriverFactory($this->createConfigMock(), new RouteCollection([]));
- }
-
public function testThrowIfPackageThatSupportSchemeNotInstalled()
{
$scheme = 'scheme5b7aa7d7cd213';
@@ -75,9 +70,9 @@ public function testThrowIfPackageThatSupportSchemeNotInstalled()
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('To use given scheme "scheme5b7aa7d7cd213" a package has to be installed. Run "composer req thePackage theOtherPackage" to add it.');
- $factory = new DriverFactory($this->createConfigMock(), new RouteCollection([]));
+ $factory = new DriverFactory();
- $factory->create($this->createConnectionFactoryMock(), $scheme.'://foo', []);
+ $factory->create($this->createConnectionFactoryMock(), $this->createDummyConfig($scheme.'://foo'), new RouteCollection([]));
}
public function testThrowIfSchemeIsNotKnown()
@@ -87,9 +82,9 @@ public function testThrowIfSchemeIsNotKnown()
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('A given scheme "scheme5b7aa862e70a5" is not supported. Maybe it is a custom driver, make sure you registered it with "Enqueue\Client\Resources::addDriver".');
- $factory = new DriverFactory($this->createConfigMock(), new RouteCollection([]));
+ $factory = new DriverFactory();
- $factory->create($this->createConnectionFactoryMock(), $scheme.'://foo', []);
+ $factory->create($this->createConnectionFactoryMock(), $this->createDummyConfig($scheme.'://foo'), new RouteCollection([]));
}
public function testThrowIfDsnInvalid()
@@ -97,9 +92,9 @@ public function testThrowIfDsnInvalid()
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The DSN is invalid. It does not have scheme separator ":".');
- $factory = new DriverFactory($this->createConfigMock(), new RouteCollection([]));
+ $factory = new DriverFactory();
- $factory->create($this->createConnectionFactoryMock(), 'invalidDsn', []);
+ $factory->create($this->createConnectionFactoryMock(), $this->createDummyConfig('invalidDsn'), new RouteCollection([]));
}
/**
@@ -110,7 +105,7 @@ public function testReturnsExpectedFactories(
string $connectionFactoryClass,
string $contextClass,
array $conifg,
- string $expectedDriverClass
+ string $expectedDriverClass,
) {
$connectionFactoryMock = $this->createMock($connectionFactoryClass);
$connectionFactoryMock
@@ -119,9 +114,9 @@ public function testReturnsExpectedFactories(
->willReturn($this->createMock($contextClass))
;
- $driverFactory = new DriverFactory($this->createConfigMock(), new RouteCollection([]));
+ $driverFactory = new DriverFactory();
- $driver = $driverFactory->create($connectionFactoryMock, $dsn, $conifg);
+ $driver = $driverFactory->create($connectionFactoryMock, $this->createDummyConfig($dsn), new RouteCollection([]));
$this->assertInstanceOf($expectedDriverClass, $driver);
}
@@ -139,7 +134,7 @@ public static function provideDSN()
yield ['file:', FsConnectionFactory::class, FsContext::class, [], FsDriver::class];
// https://github.com/php-enqueue/enqueue-dev/issues/511
-// yield ['gearman:', GearmanConnectionFactory::class, NullContext::class, [], NullDriver::class];
+ // yield ['gearman:', GearmanConnectionFactory::class, NullContext::class, [], NullDriver::class];
yield ['gps:', GpsConnectionFactory::class, GpsContext::class, [], GpsDriver::class];
@@ -164,6 +159,21 @@ public static function provideDSN()
yield ['beanstalk:', PheanstalkConnectionFactory::class, PheanstalkContext::class, [], GenericDriver::class];
}
+ private function createDummyConfig(string $dsn): Config
+ {
+ return Config::create(
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ['dsn' => $dsn],
+ []
+ );
+ }
+
private function createConnectionFactoryMock(): ConnectionFactory
{
return $this->createMock(ConnectionFactory::class);
diff --git a/pkg/enqueue/Tests/Client/DriverPreSendTest.php b/pkg/enqueue/Tests/Client/DriverPreSendTest.php
index d31ac17f1..32af2a81f 100644
--- a/pkg/enqueue/Tests/Client/DriverPreSendTest.php
+++ b/pkg/enqueue/Tests/Client/DriverPreSendTest.php
@@ -19,15 +19,6 @@ public function testShouldBeFinal()
self::assertClassFinal(DriverPreSend::class);
}
- public function testCouldBeConstructedWithExpectedArguments()
- {
- new DriverPreSend(
- new Message(),
- $this->createProducerMock(),
- $this->createDriverMock()
- );
- }
-
public function testShouldAllowGetArgumentSetInConstructor()
{
$expectedMessage = new Message();
@@ -76,7 +67,7 @@ public function testShouldAllowGetTopic()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createDriverMock(): DriverInterface
{
@@ -84,7 +75,7 @@ private function createDriverMock(): DriverInterface
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createProducerMock(): ProducerInterface
{
diff --git a/pkg/enqueue/Tests/Client/Extension/PrepareBodyExtensionTest.php b/pkg/enqueue/Tests/Client/Extension/PrepareBodyExtensionTest.php
index b1fd98509..c3032ccc8 100644
--- a/pkg/enqueue/Tests/Client/Extension/PrepareBodyExtensionTest.php
+++ b/pkg/enqueue/Tests/Client/Extension/PrepareBodyExtensionTest.php
@@ -4,9 +4,10 @@
use Enqueue\Client\DriverInterface;
use Enqueue\Client\Extension\PrepareBodyExtension;
-use Enqueue\Client\ExtensionInterface;
use Enqueue\Client\Message;
use Enqueue\Client\PreSend;
+use Enqueue\Client\PreSendCommandExtensionInterface;
+use Enqueue\Client\PreSendEventExtensionInterface;
use Enqueue\Client\ProducerInterface;
use Enqueue\Tests\Mocks\JsonSerializableObject;
use PHPUnit\Framework\TestCase;
@@ -17,25 +18,20 @@ public function testShouldImplementExtensionInterface()
{
$rc = new \ReflectionClass(PrepareBodyExtension::class);
- $this->assertTrue($rc->implementsInterface(ExtensionInterface::class));
- }
-
- public function testCouldConstructedWithoutAnyArguments()
- {
- new PrepareBodyExtension();
+ $this->assertTrue($rc->implementsInterface(PreSendEventExtensionInterface::class));
+ $this->assertTrue($rc->implementsInterface(PreSendCommandExtensionInterface::class));
}
/**
* @dataProvider provideMessages
*
- * @param mixed $body
- * @param null|mixed $contentType
+ * @param mixed|null $contentType
*/
public function testShouldSendStringUnchangedAndAddPlainTextContentTypeIfEmpty(
$body,
$contentType,
string $expectedBody,
- string $expectedContentType
+ string $expectedContentType,
) {
$message = new Message($body);
$message->setContentType($contentType);
diff --git a/pkg/enqueue/Tests/Client/PostSendTest.php b/pkg/enqueue/Tests/Client/PostSendTest.php
index 65860766e..ba51710e7 100644
--- a/pkg/enqueue/Tests/Client/PostSendTest.php
+++ b/pkg/enqueue/Tests/Client/PostSendTest.php
@@ -8,6 +8,8 @@
use Enqueue\Client\PostSend;
use Enqueue\Client\ProducerInterface;
use Enqueue\Test\ClassExtensionTrait;
+use Interop\Queue\Destination;
+use Interop\Queue\Message as TransportMessage;
use PHPUnit\Framework\TestCase;
class PostSendTest extends TestCase
@@ -19,30 +21,27 @@ public function testShouldBeFinal()
self::assertClassFinal(PostSend::class);
}
- public function testCouldBeConstructedWithExpectedArguments()
- {
- new PostSend(
- new Message(),
- $this->createProducerMock(),
- $this->createDriverMock()
- );
- }
-
public function testShouldAllowGetArgumentSetInConstructor()
{
$expectedMessage = new Message();
$expectedProducer = $this->createProducerMock();
$expectedDriver = $this->createDriverMock();
+ $expectedDestination = $this->createDestinationMock();
+ $expectedTransportMessage = $this->createTransportMessageMock();
$context = new PostSend(
$expectedMessage,
$expectedProducer,
- $expectedDriver
+ $expectedDriver,
+ $expectedDestination,
+ $expectedTransportMessage
);
$this->assertSame($expectedMessage, $context->getMessage());
$this->assertSame($expectedProducer, $context->getProducer());
$this->assertSame($expectedDriver, $context->getDriver());
+ $this->assertSame($expectedDestination, $context->getTransportDestination());
+ $this->assertSame($expectedTransportMessage, $context->getTransportMessage());
}
public function testShouldAllowGetCommand()
@@ -53,7 +52,9 @@ public function testShouldAllowGetCommand()
$context = new PostSend(
$message,
$this->createProducerMock(),
- $this->createDriverMock()
+ $this->createDriverMock(),
+ $this->createDestinationMock(),
+ $this->createTransportMessageMock()
);
$this->assertFalse($context->isEvent());
@@ -68,7 +69,9 @@ public function testShouldAllowGetTopic()
$context = new PostSend(
$message,
$this->createProducerMock(),
- $this->createDriverMock()
+ $this->createDriverMock(),
+ $this->createDestinationMock(),
+ $this->createTransportMessageMock()
);
$this->assertTrue($context->isEvent());
@@ -76,7 +79,7 @@ public function testShouldAllowGetTopic()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createDriverMock(): DriverInterface
{
@@ -84,10 +87,26 @@ private function createDriverMock(): DriverInterface
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createProducerMock(): ProducerInterface
{
return $this->createMock(ProducerInterface::class);
}
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|Destination
+ */
+ private function createDestinationMock(): Destination
+ {
+ return $this->createMock(Destination::class);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|TransportMessage
+ */
+ private function createTransportMessageMock(): TransportMessage
+ {
+ return $this->createMock(TransportMessage::class);
+ }
}
diff --git a/pkg/enqueue/Tests/Client/PreSendTest.php b/pkg/enqueue/Tests/Client/PreSendTest.php
index d1e5595ba..01a7e5055 100644
--- a/pkg/enqueue/Tests/Client/PreSendTest.php
+++ b/pkg/enqueue/Tests/Client/PreSendTest.php
@@ -18,16 +18,6 @@ public function testShouldBeFinal()
self::assertClassFinal(PreSend::class);
}
- public function testCouldBeConstructedWithExpectedArguments()
- {
- new PreSend(
- 'aCommandOrTopic',
- new Message(),
- $this->createProducerMock(),
- $this->createDriverMock()
- );
- }
-
public function testShouldAllowGetArgumentSetInConstructor()
{
$expectedCommandOrTopic = 'theCommandOrTopic';
@@ -61,7 +51,7 @@ public function testCouldChangeTopic()
$this->createDriverMock()
);
- //guard
+ // guard
$this->assertSame('aCommandOrTopic', $context->getTopic());
$context->changeTopic('theChangedTopic');
@@ -78,7 +68,7 @@ public function testCouldChangeCommand()
$this->createDriverMock()
);
- //guard
+ // guard
$this->assertSame('aCommandOrTopic', $context->getCommand());
$context->changeCommand('theChangedCommand');
@@ -95,7 +85,7 @@ public function testCouldChangeBody()
$this->createDriverMock()
);
- //guard
+ // guard
$this->assertSame('aBody', $context->getMessage()->getBody());
$this->assertNull($context->getMessage()->getContentType());
@@ -109,7 +99,7 @@ public function testCouldChangeBody()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createDriverMock(): DriverInterface
{
@@ -117,7 +107,7 @@ private function createDriverMock(): DriverInterface
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createProducerMock(): ProducerInterface
{
diff --git a/pkg/enqueue/Tests/Client/ProducerSendCommandTest.php b/pkg/enqueue/Tests/Client/ProducerSendCommandTest.php
index 92885aa12..9500e9d62 100644
--- a/pkg/enqueue/Tests/Client/ProducerSendCommandTest.php
+++ b/pkg/enqueue/Tests/Client/ProducerSendCommandTest.php
@@ -2,9 +2,11 @@
namespace Enqueue\Tests\Client;
+use Enqueue\Client\ChainExtension;
use Enqueue\Client\Config;
use Enqueue\Client\DriverInterface;
use Enqueue\Client\DriverPreSend;
+use Enqueue\Client\DriverSendResult;
use Enqueue\Client\ExtensionInterface;
use Enqueue\Client\Message;
use Enqueue\Client\MessagePriority;
@@ -15,6 +17,8 @@
use Enqueue\Rpc\RpcFactory;
use Enqueue\Test\ClassExtensionTrait;
use Enqueue\Tests\Mocks\CustomPrepareBodyClientExtension;
+use Interop\Queue\Destination;
+use Interop\Queue\Message as TransportMessage;
use PHPUnit\Framework\TestCase;
class ProducerSendCommandTest extends TestCase
@@ -30,6 +34,7 @@ public function testShouldSendCommandToProcessor()
->expects($this->once())
->method('sendToProcessor')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$driver
->expects($this->never())
@@ -55,6 +60,7 @@ public function testShouldSendCommandWithReply()
->expects($this->once())
->method('sendToProcessor')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$driver
->expects($this->never())
@@ -100,6 +106,7 @@ public function testShouldSendCommandWithReplyAndCustomReplyQueueAndCorrelationI
->expects($this->once())
->method('sendToProcessor')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$driver
->expects($this->never())
@@ -140,6 +147,11 @@ public function testShouldOverwriteExpectedMessageProperties()
$message->setScope('scopeShouldBeOverwritten');
$driver = $this->createDriverStub();
+ $driver
+ ->expects($this->once())
+ ->method('sendToProcessor')
+ ->willReturn($this->createDriverSendResult())
+ ;
$producer = new Producer($driver, $this->createRpcFactoryMock());
$producer->sendCommand('expectedCommand', $message);
@@ -161,6 +173,7 @@ public function testShouldSendCommandWithoutPriorityByDefault()
->expects($this->once())
->method('sendToProcessor')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -179,6 +192,7 @@ public function testShouldSendCommandWithCustomPriority()
->expects($this->once())
->method('sendToProcessor')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -196,6 +210,7 @@ public function testShouldSendCommandWithGeneratedMessageId()
->expects($this->once())
->method('sendToProcessor')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -214,6 +229,7 @@ public function testShouldSendCommandWithCustomMessageId()
->expects($this->once())
->method('sendToProcessor')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -231,6 +247,7 @@ public function testShouldSendCommandWithGeneratedTimestamp()
->expects($this->once())
->method('sendToProcessor')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -249,6 +266,7 @@ public function testShouldSendCommandWithCustomTimestamp()
->expects($this->once())
->method('sendToProcessor')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -265,6 +283,8 @@ public function testShouldSerializeMessageToJsonByDefault()
->method('sendToProcessor')
->willReturnCallback(function (Message $message) {
$this->assertSame('{"foo":"fooVal"}', $message->getBody());
+
+ return $this->createDriverSendResult();
})
;
@@ -280,10 +300,12 @@ public function testShouldSerializeMessageByCustomExtension()
->method('sendToProcessor')
->willReturnCallback(function (Message $message) {
$this->assertSame('theCommandBodySerializedByCustomExtension', $message->getBody());
+
+ return $this->createDriverSendResult();
})
;
- $producer = new Producer($driver, $this->createRpcFactoryMock(), new CustomPrepareBodyClientExtension());
+ $producer = new Producer($driver, $this->createRpcFactoryMock(), new ChainExtension([new CustomPrepareBodyClientExtension()]));
$producer->sendCommand('command', ['foo' => 'fooVal']);
}
@@ -301,6 +323,8 @@ public function testShouldSendCommandToApplicationRouter()
self::assertSame('aBody', $message->getBody());
self::assertNull($message->getProperty(Config::PROCESSOR));
self::assertSame('command', $message->getProperty(Config::COMMAND));
+
+ return $this->createDriverSendResult();
})
;
@@ -338,6 +362,7 @@ public function testShouldCallPreSendCommandExtensionMethodWhenSendToBus()
$driver
->expects($this->once())
->method('sendToProcessor')
+ ->willReturn($this->createDriverSendResult())
;
$extension = $this->createMock(ExtensionInterface::class);
@@ -375,6 +400,7 @@ public function testShouldCallPreSendCommandExtensionMethodWhenSendToApplication
$driver
->expects($this->once())
->method('sendToProcessor')
+ ->willReturn($this->createDriverSendResult())
;
$extension = $this->createMock(ExtensionInterface::class);
@@ -412,6 +438,7 @@ public function testShouldCallPreDriverSendExtensionMethod()
$driver
->expects($this->once())
->method('sendToProcessor')
+ ->willReturn($this->createDriverSendResult())
;
$extension = $this->createMock(ExtensionInterface::class);
@@ -443,6 +470,7 @@ public function testShouldCallPostSendExtensionMethod()
$driver
->expects($this->once())
->method('sendToProcessor')
+ ->willReturn($this->createDriverSendResult())
;
$extension = $this->createMock(ExtensionInterface::class);
@@ -451,7 +479,7 @@ public function testShouldCallPostSendExtensionMethod()
$extension
->expects($this->at(0))
- ->method('onDriverPreSend')
+ ->method('onPostSend')
->willReturnCallback(function (PostSend $context) use ($message, $producer, $driver) {
$this->assertSame($message, $context->getMessage());
$this->assertSame($producer, $context->getProducer());
@@ -465,7 +493,7 @@ public function testShouldCallPostSendExtensionMethod()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createRpcFactoryMock(): RpcFactory
{
@@ -473,17 +501,20 @@ private function createRpcFactoryMock(): RpcFactory
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createDriverStub(): DriverInterface
{
$config = new Config(
'a_prefix',
+ '.',
'an_app',
'a_router_topic',
'a_router_queue',
'a_default_processor_queue',
- 'a_router_processor_name'
+ 'a_router_processor_name',
+ [],
+ []
);
$driverMock = $this->createMock(DriverInterface::class);
@@ -495,4 +526,12 @@ private function createDriverStub(): DriverInterface
return $driverMock;
}
+
+ private function createDriverSendResult(): DriverSendResult
+ {
+ return new DriverSendResult(
+ $this->createMock(Destination::class),
+ $this->createMock(TransportMessage::class)
+ );
+ }
}
diff --git a/pkg/enqueue/Tests/Client/ProducerSendEventTest.php b/pkg/enqueue/Tests/Client/ProducerSendEventTest.php
index 0fdd780c9..c92b49560 100644
--- a/pkg/enqueue/Tests/Client/ProducerSendEventTest.php
+++ b/pkg/enqueue/Tests/Client/ProducerSendEventTest.php
@@ -2,9 +2,11 @@
namespace Enqueue\Tests\Client;
+use Enqueue\Client\ChainExtension;
use Enqueue\Client\Config;
use Enqueue\Client\DriverInterface;
use Enqueue\Client\DriverPreSend;
+use Enqueue\Client\DriverSendResult;
use Enqueue\Client\ExtensionInterface;
use Enqueue\Client\Message;
use Enqueue\Client\MessagePriority;
@@ -13,6 +15,8 @@
use Enqueue\Client\Producer;
use Enqueue\Rpc\RpcFactory;
use Enqueue\Tests\Mocks\CustomPrepareBodyClientExtension;
+use Interop\Queue\Destination;
+use Interop\Queue\Message as TransportMessage;
use PHPUnit\Framework\TestCase;
class ProducerSendEventTest extends TestCase
@@ -26,6 +30,7 @@ public function testShouldSendEventToRouter()
->expects($this->once())
->method('sendToRouter')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$driver
->expects($this->never())
@@ -48,6 +53,12 @@ public function testShouldOverwriteTopicProperty()
$message->setProperty(Config::TOPIC, 'topicShouldBeOverwritten');
$driver = $this->createDriverStub();
+ $driver
+ ->expects($this->once())
+ ->method('sendToRouter')
+ ->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
+ ;
$producer = new Producer($driver, $this->createRpcFactoryMock());
$producer->sendEvent('expectedTopic', $message);
@@ -68,6 +79,7 @@ public function testShouldSendEventWithoutPriorityByDefault()
->expects($this->once())
->method('sendToRouter')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -86,6 +98,7 @@ public function testShouldSendEventWithCustomPriority()
->expects($this->once())
->method('sendToRouter')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -103,6 +116,7 @@ public function testShouldSendEventWithGeneratedMessageId()
->expects($this->once())
->method('sendToRouter')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -121,6 +135,7 @@ public function testShouldSendEventWithCustomMessageId()
->expects($this->once())
->method('sendToRouter')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -138,6 +153,7 @@ public function testShouldSendEventWithGeneratedTimestamp()
->expects($this->once())
->method('sendToRouter')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -156,6 +172,7 @@ public function testShouldSendEventWithCustomTimestamp()
->expects($this->once())
->method('sendToRouter')
->with(self::identicalTo($message))
+ ->willReturn($this->createDriverSendResult())
;
$producer = new Producer($driver, $this->createRpcFactoryMock());
@@ -172,6 +189,8 @@ public function testShouldSerializeMessageToJsonByDefault()
->method('sendToRouter')
->willReturnCallback(function (Message $message) {
$this->assertSame('{"foo":"fooVal"}', $message->getBody());
+
+ return $this->createDriverSendResult();
})
;
@@ -187,10 +206,12 @@ public function testShouldSerializeMessageByCustomExtension()
->method('sendToRouter')
->willReturnCallback(function (Message $message) {
$this->assertSame('theEventBodySerializedByCustomExtension', $message->getBody());
+
+ return $this->createDriverSendResult();
})
;
- $producer = new Producer($driver, $this->createRpcFactoryMock(), new CustomPrepareBodyClientExtension());
+ $producer = new Producer($driver, $this->createRpcFactoryMock(), new ChainExtension([new CustomPrepareBodyClientExtension()]));
$producer->sendEvent('topic', ['foo' => 'fooVal']);
}
@@ -236,6 +257,8 @@ public function testShouldSendEventToApplicationRouter()
// null means a driver sends a message to router processor.
self::assertNull($message->getProperty(Config::PROCESSOR));
+
+ return $this->createDriverSendResult();
})
;
@@ -295,6 +318,7 @@ public function testShouldCallPreSendEventExtensionMethodWhenSendToBus()
$driver
->expects($this->once())
->method('sendToRouter')
+ ->willReturn($this->createDriverSendResult())
;
$extension = $this->createMock(ExtensionInterface::class);
@@ -332,6 +356,7 @@ public function testShouldCallPreSendEventExtensionMethodWhenSendToApplicationRo
$driver
->expects($this->once())
->method('sendToProcessor')
+ ->willReturn($this->createDriverSendResult())
;
$extension = $this->createMock(ExtensionInterface::class);
@@ -369,6 +394,7 @@ public function testShouldCallPreDriverSendExtensionMethodWhenSendToMessageBus()
$driver
->expects($this->once())
->method('sendToRouter')
+ ->willReturn($this->createDriverSendResult())
;
$extension = $this->createMock(ExtensionInterface::class);
@@ -400,6 +426,7 @@ public function testShouldCallPreDriverSendExtensionMethodWhenSendToApplicationR
$driver
->expects($this->once())
->method('sendToProcessor')
+ ->willReturn($this->createDriverSendResult())
;
$extension = $this->createMock(ExtensionInterface::class);
@@ -431,6 +458,7 @@ public function testShouldCallPostSendExtensionMethodWhenSendToMessageBus()
$driver
->expects($this->once())
->method('sendToRouter')
+ ->willReturn($this->createDriverSendResult())
;
$extension = $this->createMock(ExtensionInterface::class);
@@ -462,6 +490,7 @@ public function testShouldCallPostSendExtensionMethodWhenSendToApplicationRouter
$driver
->expects($this->once())
->method('sendToProcessor')
+ ->willReturn($this->createDriverSendResult())
;
$extension = $this->createMock(ExtensionInterface::class);
@@ -470,7 +499,7 @@ public function testShouldCallPostSendExtensionMethodWhenSendToApplicationRouter
$extension
->expects($this->at(0))
- ->method('onDriverPreSend')
+ ->method('onPostSend')
->willReturnCallback(function (PostSend $context) use ($message, $producer, $driver) {
$this->assertSame($message, $context->getMessage());
$this->assertSame($producer, $context->getProducer());
@@ -484,7 +513,7 @@ public function testShouldCallPostSendExtensionMethodWhenSendToApplicationRouter
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createRpcFactoryMock(): RpcFactory
{
@@ -492,17 +521,20 @@ private function createRpcFactoryMock(): RpcFactory
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createDriverStub(): DriverInterface
{
$config = new Config(
'a_prefix',
+ '.',
'an_app',
'a_router_topic',
'a_router_queue',
'a_default_processor_queue',
- 'a_router_processor_name'
+ 'a_router_processor_name',
+ [],
+ []
);
$driverMock = $this->createMock(DriverInterface::class);
@@ -514,4 +546,12 @@ private function createDriverStub(): DriverInterface
return $driverMock;
}
+
+ private function createDriverSendResult(): DriverSendResult
+ {
+ return new DriverSendResult(
+ $this->createMock(Destination::class),
+ $this->createMock(TransportMessage::class)
+ );
+ }
}
diff --git a/pkg/enqueue/Tests/Client/ProducerTest.php b/pkg/enqueue/Tests/Client/ProducerTest.php
index 4fbf4baea..23b004ac3 100644
--- a/pkg/enqueue/Tests/Client/ProducerTest.php
+++ b/pkg/enqueue/Tests/Client/ProducerTest.php
@@ -3,7 +3,6 @@
namespace Enqueue\Tests\Client;
use Enqueue\Client\DriverInterface;
-use Enqueue\Client\ExtensionInterface;
use Enqueue\Client\Producer;
use Enqueue\Client\ProducerInterface;
use Enqueue\Rpc\RpcFactory;
@@ -24,22 +23,8 @@ public function testShouldBeFinal()
self::assertClassFinal(Producer::class);
}
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new Producer($this->createDriverMock(), $this->createRpcFactoryMock());
- }
-
- public function testCouldBeConstructedWithOptionalArguments()
- {
- new Producer(
- $this->createDriverMock(),
- $this->createRpcFactoryMock(),
- $this->createMock(ExtensionInterface::class)
- );
- }
-
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createRpcFactoryMock(): RpcFactory
{
@@ -47,7 +32,7 @@ private function createRpcFactoryMock(): RpcFactory
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createDriverMock(): DriverInterface
{
diff --git a/pkg/enqueue/Tests/Client/ResourcesTest.php b/pkg/enqueue/Tests/Client/ResourcesTest.php
index 7311f31d0..e79fb9dda 100644
--- a/pkg/enqueue/Tests/Client/ResourcesTest.php
+++ b/pkg/enqueue/Tests/Client/ResourcesTest.php
@@ -28,13 +28,13 @@ public function testShouldGetAvailableDriverInExpectedFormat()
{
$availableDrivers = Resources::getAvailableDrivers();
- $this->assertInternalType('array', $availableDrivers);
+ self::assertIsArray($availableDrivers);
$this->assertGreaterThan(0, count($availableDrivers));
$driverInfo = $availableDrivers[0];
- $this->assertArrayHasKey('factoryClass', $driverInfo);
- $this->assertSame(AmqpDriver::class, $driverInfo['factoryClass']);
+ $this->assertArrayHasKey('driverClass', $driverInfo);
+ $this->assertSame(AmqpDriver::class, $driverInfo['driverClass']);
$this->assertArrayHasKey('schemes', $driverInfo);
$this->assertSame(['amqp', 'amqps'], $driverInfo['schemes']);
@@ -50,13 +50,13 @@ public function testShouldGetAvailableDriverWithRequiredExtensionInExpectedForma
{
$availableDrivers = Resources::getAvailableDrivers();
- $this->assertInternalType('array', $availableDrivers);
+ self::assertIsArray($availableDrivers);
$this->assertGreaterThan(0, count($availableDrivers));
$driverInfo = $availableDrivers[1];
- $this->assertArrayHasKey('factoryClass', $driverInfo);
- $this->assertSame(RabbitMqDriver::class, $driverInfo['factoryClass']);
+ $this->assertArrayHasKey('driverClass', $driverInfo);
+ $this->assertSame(RabbitMqDriver::class, $driverInfo['driverClass']);
$this->assertArrayHasKey('schemes', $driverInfo);
$this->assertSame(['amqp', 'amqps'], $driverInfo['schemes']);
@@ -72,13 +72,13 @@ public function testShouldGetKnownDriversInExpectedFormat()
{
$knownDrivers = Resources::getAvailableDrivers();
- $this->assertInternalType('array', $knownDrivers);
+ self::assertIsArray($knownDrivers);
$this->assertGreaterThan(0, count($knownDrivers));
$driverInfo = $knownDrivers[0];
- $this->assertArrayHasKey('factoryClass', $driverInfo);
- $this->assertSame(AmqpDriver::class, $driverInfo['factoryClass']);
+ $this->assertArrayHasKey('driverClass', $driverInfo);
+ $this->assertSame(AmqpDriver::class, $driverInfo['driverClass']);
$this->assertArrayHasKey('schemes', $driverInfo);
$this->assertSame(['amqp', 'amqps'], $driverInfo['schemes']);
@@ -126,7 +126,7 @@ public function testShouldAllowRegisterDriverThatIsNotInstalled()
$driverInfo = end($availableDrivers);
- $this->assertSame('theDriverClass', $driverInfo['factoryClass']);
+ $this->assertSame('theDriverClass', $driverInfo['driverClass']);
}
public function testShouldAllowGetPreviouslyRegisteredDriver()
@@ -144,8 +144,8 @@ public function testShouldAllowGetPreviouslyRegisteredDriver()
$driverInfo = end($availableDrivers);
- $this->assertArrayHasKey('factoryClass', $driverInfo);
- $this->assertSame($driverClass, $driverInfo['factoryClass']);
+ $this->assertArrayHasKey('driverClass', $driverInfo);
+ $this->assertSame($driverClass, $driverInfo['driverClass']);
$this->assertArrayHasKey('schemes', $driverInfo);
$this->assertSame(['fooscheme', 'barscheme'], $driverInfo['schemes']);
diff --git a/pkg/enqueue/Tests/Client/RouterProcessorTest.php b/pkg/enqueue/Tests/Client/RouterProcessorTest.php
index 3a4596b0f..7d2971189 100644
--- a/pkg/enqueue/Tests/Client/RouterProcessorTest.php
+++ b/pkg/enqueue/Tests/Client/RouterProcessorTest.php
@@ -4,6 +4,7 @@
use Enqueue\Client\Config;
use Enqueue\Client\DriverInterface;
+use Enqueue\Client\DriverSendResult;
use Enqueue\Client\Message;
use Enqueue\Client\Route;
use Enqueue\Client\RouteCollection;
@@ -12,12 +13,16 @@
use Enqueue\Null\NullContext;
use Enqueue\Null\NullMessage;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
+use Interop\Queue\Destination;
+use Interop\Queue\Message as TransportMessage;
use Interop\Queue\Processor;
use PHPUnit\Framework\TestCase;
class RouterProcessorTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testShouldImplementProcessorInterface()
{
@@ -83,6 +88,8 @@ public function testShouldRouteOriginalMessageToAllRecipients()
->method('sendToProcessor')
->willReturnCallback(function (Message $message) use ($routedMessages) {
$routedMessages->append($message);
+
+ return $this->createDriverSendResult();
})
;
$driver
@@ -167,6 +174,8 @@ public function testShouldDoNotModifyOriginalMessage()
->method('sendToProcessor')
->willReturnCallback(function (Message $message) use ($routedMessages) {
$routedMessages->append($message);
+
+ return $this->createDriverSendResult();
});
$driver
->expects($this->atLeastOnce())
@@ -179,7 +188,7 @@ public function testShouldDoNotModifyOriginalMessage()
$result = $processor->process($message, new NullContext());
- //guard
+ // guard
$this->assertEquals(Result::ACK, $result->getStatus());
$this->assertSame('theBody', $message->getBody());
@@ -188,17 +197,25 @@ public function testShouldDoNotModifyOriginalMessage()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject|DriverInterface
*/
- private function createDriverStub(RouteCollection $routeCollection = null): DriverInterface
+ private function createDriverStub(?RouteCollection $routeCollection = null): DriverInterface
{
$driver = $this->createMock(DriverInterface::class);
$driver
->expects($this->any())
->method('getRouteCollection')
- ->willReturn($routeCollection)
+ ->willReturn($routeCollection ?? new RouteCollection([]))
;
return $driver;
}
+
+ private function createDriverSendResult(): DriverSendResult
+ {
+ return new DriverSendResult(
+ $this->createMock(Destination::class),
+ $this->createMock(TransportMessage::class)
+ );
+ }
}
diff --git a/pkg/enqueue/Tests/Client/SpoolProducerTest.php b/pkg/enqueue/Tests/Client/SpoolProducerTest.php
index 8c00dedcd..014fe4962 100644
--- a/pkg/enqueue/Tests/Client/SpoolProducerTest.php
+++ b/pkg/enqueue/Tests/Client/SpoolProducerTest.php
@@ -18,11 +18,6 @@ public function testShouldImplementProducerInterface()
self::assertClassImplements(ProducerInterface::class, SpoolProducer::class);
}
- public function testCouldBeConstructedWithRealProducer()
- {
- new SpoolProducer($this->createProducerMock());
- }
-
public function testShouldQueueEventMessageOnSend()
{
$message = new Message();
@@ -154,7 +149,7 @@ public function testShouldSendImmediatelyCommandMessageWithNeedReplyTrue()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ProducerInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|ProducerInterface
*/
protected function createProducerMock()
{
diff --git a/pkg/enqueue/Tests/Client/TraceableProducerTest.php b/pkg/enqueue/Tests/Client/TraceableProducerTest.php
index 82364cacc..b0df066ce 100644
--- a/pkg/enqueue/Tests/Client/TraceableProducerTest.php
+++ b/pkg/enqueue/Tests/Client/TraceableProducerTest.php
@@ -2,6 +2,7 @@
namespace Enqueue\Tests\Client;
+use DMS\PHPUnitExtensions\ArraySubset\Assert;
use Enqueue\Client\Message;
use Enqueue\Client\ProducerInterface;
use Enqueue\Client\TraceableProducer;
@@ -17,11 +18,6 @@ public function testShouldImplementProducerInterface()
$this->assertClassImplements(ProducerInterface::class, TraceableProducer::class);
}
- public function testCouldBeConstructedWithInternalMessageProducer()
- {
- new TraceableProducer($this->createProducerMock());
- }
-
public function testShouldPassAllArgumentsToInternalEventMessageProducerSendMethod()
{
$topic = 'theTopic';
@@ -45,7 +41,7 @@ public function testShouldCollectInfoIfStringGivenAsEventMessage()
$producer->sendEvent('aFooTopic', 'aFooBody');
- $this->assertSame([
+ Assert::assertArraySubset([
[
'topic' => 'aFooTopic',
'command' => null,
@@ -60,6 +56,8 @@ public function testShouldCollectInfoIfStringGivenAsEventMessage()
'messageId' => null,
],
], $producer->getTraces());
+
+ $this->assertArrayHasKey('sentAt', $producer->getTraces()[0]);
}
public function testShouldCollectInfoIfArrayGivenAsEventMessage()
@@ -68,7 +66,7 @@ public function testShouldCollectInfoIfArrayGivenAsEventMessage()
$producer->sendEvent('aFooTopic', ['foo' => 'fooVal', 'bar' => 'barVal']);
- $this->assertSame([
+ Assert::assertArraySubset([
[
'topic' => 'aFooTopic',
'command' => null,
@@ -83,6 +81,8 @@ public function testShouldCollectInfoIfArrayGivenAsEventMessage()
'messageId' => null,
],
], $producer->getTraces());
+
+ $this->assertArrayHasKey('sentAt', $producer->getTraces()[0]);
}
public function testShouldCollectInfoIfEventMessageObjectGivenAsMessage()
@@ -102,7 +102,7 @@ public function testShouldCollectInfoIfEventMessageObjectGivenAsMessage()
$producer->sendEvent('aFooTopic', $message);
- $this->assertSame([
+ Assert::assertArraySubset([
[
'topic' => 'aFooTopic',
'command' => null,
@@ -117,6 +117,8 @@ public function testShouldCollectInfoIfEventMessageObjectGivenAsMessage()
'messageId' => 'theMessageId',
],
], $producer->getTraces());
+
+ $this->assertArrayHasKey('sentAt', $producer->getTraces()[0]);
}
public function testShouldNotStoreAnythingIfInternalEventMessageProducerThrowsException()
@@ -162,7 +164,7 @@ public function testShouldCollectInfoIfStringGivenAsCommandMessage()
$producer->sendCommand('aFooCommand', 'aFooBody');
- $this->assertSame([
+ Assert::assertArraySubset([
[
'topic' => null,
'command' => 'aFooCommand',
@@ -177,6 +179,8 @@ public function testShouldCollectInfoIfStringGivenAsCommandMessage()
'messageId' => null,
],
], $producer->getTraces());
+
+ $this->assertArrayHasKey('sentAt', $producer->getTraces()[0]);
}
public function testShouldCollectInfoIfArrayGivenAsCommandMessage()
@@ -185,7 +189,7 @@ public function testShouldCollectInfoIfArrayGivenAsCommandMessage()
$producer->sendCommand('aFooCommand', ['foo' => 'fooVal', 'bar' => 'barVal']);
- $this->assertSame([
+ Assert::assertArraySubset([
[
'topic' => null,
'command' => 'aFooCommand',
@@ -200,6 +204,8 @@ public function testShouldCollectInfoIfArrayGivenAsCommandMessage()
'messageId' => null,
],
], $producer->getTraces());
+
+ $this->assertArrayHasKey('sentAt', $producer->getTraces()[0]);
}
public function testShouldCollectInfoIfCommandMessageObjectGivenAsMessage()
@@ -219,7 +225,7 @@ public function testShouldCollectInfoIfCommandMessageObjectGivenAsMessage()
$producer->sendCommand('aFooCommand', $message);
- $this->assertSame([
+ Assert::assertArraySubset([
[
'topic' => null,
'command' => 'aFooCommand',
@@ -234,6 +240,8 @@ public function testShouldCollectInfoIfCommandMessageObjectGivenAsMessage()
'messageId' => 'theMessageId',
],
], $producer->getTraces());
+
+ $this->assertArrayHasKey('sentAt', $producer->getTraces()[0]);
}
public function testShouldNotStoreAnythingIfInternalCommandMessageProducerThrowsException()
@@ -263,9 +271,9 @@ public function testShouldAllowGetInfoSentToSameTopic()
$producer->sendEvent('aFooTopic', 'aFooBody');
$producer->sendEvent('aFooTopic', 'aFooBody');
- $this->assertArraySubset([
- ['topic' => 'aFooTopic', 'body' => 'aFooBody'],
- ['topic' => 'aFooTopic', 'body' => 'aFooBody'],
+ Assert::assertArraySubset([
+ ['topic' => 'aFooTopic', 'body' => 'aFooBody'],
+ ['topic' => 'aFooTopic', 'body' => 'aFooBody'],
], $producer->getTraces());
}
@@ -276,7 +284,7 @@ public function testShouldAllowGetInfoSentToDifferentTopics()
$producer->sendEvent('aFooTopic', 'aFooBody');
$producer->sendEvent('aBarTopic', 'aBarBody');
- $this->assertArraySubset([
+ Assert::assertArraySubset([
['topic' => 'aFooTopic', 'body' => 'aFooBody'],
['topic' => 'aBarTopic', 'body' => 'aBarBody'],
], $producer->getTraces());
@@ -289,11 +297,11 @@ public function testShouldAllowGetInfoSentToSpecialTopic()
$producer->sendEvent('aFooTopic', 'aFooBody');
$producer->sendEvent('aBarTopic', 'aBarBody');
- $this->assertArraySubset([
+ Assert::assertArraySubset([
['topic' => 'aFooTopic', 'body' => 'aFooBody'],
], $producer->getTopicTraces('aFooTopic'));
- $this->assertArraySubset([
+ Assert::assertArraySubset([
['topic' => 'aBarTopic', 'body' => 'aBarBody'],
], $producer->getTopicTraces('aBarTopic'));
}
@@ -305,7 +313,7 @@ public function testShouldAllowGetInfoSentToSameCommand()
$producer->sendCommand('aFooCommand', 'aFooBody');
$producer->sendCommand('aFooCommand', 'aFooBody');
- $this->assertArraySubset([
+ Assert::assertArraySubset([
['command' => 'aFooCommand', 'body' => 'aFooBody'],
['command' => 'aFooCommand', 'body' => 'aFooBody'],
], $producer->getTraces());
@@ -318,7 +326,7 @@ public function testShouldAllowGetInfoSentToDifferentCommands()
$producer->sendCommand('aFooCommand', 'aFooBody');
$producer->sendCommand('aBarCommand', 'aBarBody');
- $this->assertArraySubset([
+ Assert::assertArraySubset([
['command' => 'aFooCommand', 'body' => 'aFooBody'],
['command' => 'aBarCommand', 'body' => 'aBarBody'],
], $producer->getTraces());
@@ -331,11 +339,11 @@ public function testShouldAllowGetInfoSentToSpecialCommand()
$producer->sendCommand('aFooCommand', 'aFooBody');
$producer->sendCommand('aBarCommand', 'aBarBody');
- $this->assertArraySubset([
+ Assert::assertArraySubset([
['command' => 'aFooCommand', 'body' => 'aFooBody'],
], $producer->getCommandTraces('aFooCommand'));
- $this->assertArraySubset([
+ Assert::assertArraySubset([
['command' => 'aBarCommand', 'body' => 'aBarBody'],
], $producer->getCommandTraces('aBarCommand'));
}
@@ -346,7 +354,7 @@ public function testShouldAllowClearStoredTraces()
$producer->sendEvent('aFooTopic', 'aFooBody');
- //guard
+ // guard
$this->assertNotEmpty($producer->getTraces());
$producer->clearTraces();
@@ -354,7 +362,7 @@ public function testShouldAllowClearStoredTraces()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ProducerInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|ProducerInterface
*/
protected function createProducerMock()
{
diff --git a/pkg/enqueue/Tests/ConnectionFactoryFactoryTest.php b/pkg/enqueue/Tests/ConnectionFactoryFactoryTest.php
index 3fb4fb57b..b6b5b4d67 100644
--- a/pkg/enqueue/Tests/ConnectionFactoryFactoryTest.php
+++ b/pkg/enqueue/Tests/ConnectionFactoryFactoryTest.php
@@ -37,11 +37,9 @@ public function testShouldBeFinal()
$this->assertTrue($rc->isFinal());
}
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new ConnectionFactoryFactory();
- }
-
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldAcceptStringDSN()
{
$factory = new ConnectionFactoryFactory();
@@ -49,6 +47,9 @@ public function testShouldAcceptStringDSN()
$factory->create('null:');
}
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldAcceptArrayWithDsnKey()
{
$factory = new ConnectionFactoryFactory();
@@ -157,7 +158,7 @@ public static function provideDSN()
yield ['file:', FsConnectionFactory::class];
// https://github.com/php-enqueue/enqueue-dev/issues/511
-// yield ['gearman:', GearmanConnectionFactory::class];
+ // yield ['gearman:', GearmanConnectionFactory::class];
yield ['gps:', GpsConnectionFactory::class];
diff --git a/pkg/enqueue/Tests/Consumption/CallbackProcessorTest.php b/pkg/enqueue/Tests/Consumption/CallbackProcessorTest.php
index f134cfe9f..86adbd3a9 100644
--- a/pkg/enqueue/Tests/Consumption/CallbackProcessorTest.php
+++ b/pkg/enqueue/Tests/Consumption/CallbackProcessorTest.php
@@ -18,12 +18,6 @@ public function testShouldImplementProcessorInterface()
$this->assertClassImplements(Processor::class, CallbackProcessor::class);
}
- public function testCouldBeConstructedWithCallableAsArgument()
- {
- new CallbackProcessor(function () {
- });
- }
-
public function testShouldCallCallbackAndProxyItsReturnedValue()
{
$expectedMessage = new NullMessage();
diff --git a/pkg/enqueue/Tests/Consumption/ChainExtensionTest.php b/pkg/enqueue/Tests/Consumption/ChainExtensionTest.php
index dcde84db3..198d00012 100644
--- a/pkg/enqueue/Tests/Consumption/ChainExtensionTest.php
+++ b/pkg/enqueue/Tests/Consumption/ChainExtensionTest.php
@@ -19,6 +19,7 @@
use Interop\Queue\Message;
use Interop\Queue\Processor;
use Interop\Queue\SubscriptionConsumer;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
@@ -32,11 +33,6 @@ public function testShouldImplementExtensionInterface()
$this->assertClassImplements(ExtensionInterface::class, ChainExtension::class);
}
- public function testCouldBeConstructedWithExtensionsArray()
- {
- new ChainExtension([$this->createExtension(), $this->createExtension()]);
- }
-
public function testShouldProxyOnInitLoggerToAllInternalExtensions()
{
$context = new InitLogger(new NullLogger());
@@ -169,6 +165,7 @@ public function testShouldProxyOnResultToAllInternalExtensions()
{
$context = new MessageResult(
$this->createInteropContextMock(),
+ $this->createInteropConsumerMock(),
$this->createMock(Message::class),
'aResult',
1,
@@ -274,7 +271,7 @@ public function testShouldProxyOnEndToAllInternalExtensions()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
protected function createLoggerMock(): LoggerInterface
{
@@ -282,7 +279,7 @@ protected function createLoggerMock(): LoggerInterface
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
protected function createInteropContextMock(): Context
{
@@ -290,7 +287,7 @@ protected function createInteropContextMock(): Context
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
protected function createInteropConsumerMock(): Consumer
{
@@ -298,7 +295,7 @@ protected function createInteropConsumerMock(): Consumer
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
protected function createInteropProcessorMock(): Processor
{
@@ -306,7 +303,7 @@ protected function createInteropProcessorMock(): Processor
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ExtensionInterface
+ * @return MockObject|ExtensionInterface
*/
protected function createExtension()
{
@@ -314,7 +311,7 @@ protected function createExtension()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createSubscriptionConsumerMock(): SubscriptionConsumer
{
diff --git a/pkg/enqueue/Tests/Consumption/Exception/IllegalContextModificationExceptionTest.php b/pkg/enqueue/Tests/Consumption/Exception/IllegalContextModificationExceptionTest.php
index 0885b500e..241f4adf9 100644
--- a/pkg/enqueue/Tests/Consumption/Exception/IllegalContextModificationExceptionTest.php
+++ b/pkg/enqueue/Tests/Consumption/Exception/IllegalContextModificationExceptionTest.php
@@ -20,9 +20,4 @@ public function testShouldExtendLogicException()
{
$this->assertClassExtends(\LogicException::class, IllegalContextModificationException::class);
}
-
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new IllegalContextModificationException();
- }
}
diff --git a/pkg/enqueue/Tests/Consumption/Exception/InvalidArgumentExceptionTest.php b/pkg/enqueue/Tests/Consumption/Exception/InvalidArgumentExceptionTest.php
index 296c76225..c1c5db362 100644
--- a/pkg/enqueue/Tests/Consumption/Exception/InvalidArgumentExceptionTest.php
+++ b/pkg/enqueue/Tests/Consumption/Exception/InvalidArgumentExceptionTest.php
@@ -21,11 +21,6 @@ public function testShouldExtendLogicException()
$this->assertClassExtends(\LogicException::class, InvalidArgumentException::class);
}
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new InvalidArgumentException();
- }
-
public function testThrowIfAssertInstanceOfNotSameAsExpected()
{
$this->expectException(InvalidArgumentException::class);
@@ -36,6 +31,9 @@ public function testThrowIfAssertInstanceOfNotSameAsExpected()
InvalidArgumentException::assertInstanceOf(new \SplStack(), \SplQueue::class);
}
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldDoNothingIfAssertDestinationInstanceOfSameAsExpected()
{
InvalidArgumentException::assertInstanceOf(new \SplQueue(), \SplQueue::class);
diff --git a/pkg/enqueue/Tests/Consumption/Exception/LogicExceptionTest.php b/pkg/enqueue/Tests/Consumption/Exception/LogicExceptionTest.php
index ddd258098..2655609ae 100644
--- a/pkg/enqueue/Tests/Consumption/Exception/LogicExceptionTest.php
+++ b/pkg/enqueue/Tests/Consumption/Exception/LogicExceptionTest.php
@@ -20,9 +20,4 @@ public function testShouldExtendLogicException()
{
$this->assertClassExtends(\LogicException::class, LogicException::class);
}
-
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new LogicException();
- }
}
diff --git a/pkg/enqueue/Tests/Consumption/Extension/LimitConsumedMessagesExtensionTest.php b/pkg/enqueue/Tests/Consumption/Extension/LimitConsumedMessagesExtensionTest.php
index 37d592e68..137e30ba4 100644
--- a/pkg/enqueue/Tests/Consumption/Extension/LimitConsumedMessagesExtensionTest.php
+++ b/pkg/enqueue/Tests/Consumption/Extension/LimitConsumedMessagesExtensionTest.php
@@ -9,17 +9,13 @@
use Interop\Queue\Context;
use Interop\Queue\Message;
use Interop\Queue\SubscriptionConsumer;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
class LimitConsumedMessagesExtensionTest extends TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new LimitConsumedMessagesExtension(12345);
- }
-
public function testOnPreConsumeShouldInterruptWhenLimitIsReached()
{
$logger = $this->createLoggerMock();
@@ -160,7 +156,7 @@ public function testOnPostReceivedShouldInterruptExecutionIfMessageLimitExceeded
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
protected function createInteropContextMock(): Context
{
@@ -168,7 +164,7 @@ protected function createInteropContextMock(): Context
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createSubscriptionConsumerMock(): SubscriptionConsumer
{
@@ -176,7 +172,7 @@ private function createSubscriptionConsumerMock(): SubscriptionConsumer
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createLoggerMock(): LoggerInterface
{
diff --git a/pkg/enqueue/Tests/Consumption/Extension/LimitConsumerMemoryExtensionTest.php b/pkg/enqueue/Tests/Consumption/Extension/LimitConsumerMemoryExtensionTest.php
index de1531ea5..25ac85895 100644
--- a/pkg/enqueue/Tests/Consumption/Extension/LimitConsumerMemoryExtensionTest.php
+++ b/pkg/enqueue/Tests/Consumption/Extension/LimitConsumerMemoryExtensionTest.php
@@ -10,20 +10,17 @@
use Interop\Queue\Context;
use Interop\Queue\Message;
use Interop\Queue\SubscriptionConsumer;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
class LimitConsumerMemoryExtensionTest extends TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new LimitConsumerMemoryExtension(12345);
- }
-
public function testShouldThrowExceptionIfMemoryLimitIsNotInt()
{
- $this->setExpectedException(\InvalidArgumentException::class, 'Expected memory limit is int but got: "double"');
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Expected memory limit is int but got: "double"');
new LimitConsumerMemoryExtension(0.0);
}
@@ -127,7 +124,7 @@ public function testOnPreConsumeShouldNotInterruptExecutionIfMemoryLimitIsNotRea
$this->assertFalse($context->isExecutionInterrupted());
// test
- $extension = new LimitConsumerMemoryExtension(PHP_INT_MAX);
+ $extension = new LimitConsumerMemoryExtension(\PHP_INT_MAX);
$extension->onPreConsume($context);
$this->assertFalse($context->isExecutionInterrupted());
@@ -148,7 +145,7 @@ public function testOnPostConsumeShouldNotInterruptExecutionIfMemoryLimitIsNotRe
$this->assertFalse($postConsume->isExecutionInterrupted());
// test
- $extension = new LimitConsumerMemoryExtension(PHP_INT_MAX);
+ $extension = new LimitConsumerMemoryExtension(\PHP_INT_MAX);
$extension->onPostConsume($postConsume);
$this->assertFalse($postConsume->isExecutionInterrupted());
@@ -169,14 +166,14 @@ public function testOnPostMessageReceivedShouldNotInterruptExecutionIfMemoryLimi
$this->assertFalse($postReceivedMessage->isExecutionInterrupted());
// test
- $extension = new LimitConsumerMemoryExtension(PHP_INT_MAX);
+ $extension = new LimitConsumerMemoryExtension(\PHP_INT_MAX);
$extension->onPostMessageReceived($postReceivedMessage);
$this->assertFalse($postReceivedMessage->isExecutionInterrupted());
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
protected function createInteropContextMock(): Context
{
@@ -184,7 +181,7 @@ protected function createInteropContextMock(): Context
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createSubscriptionConsumerMock(): SubscriptionConsumer
{
@@ -192,7 +189,7 @@ private function createSubscriptionConsumerMock(): SubscriptionConsumer
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createLoggerMock(): LoggerInterface
{
diff --git a/pkg/enqueue/Tests/Consumption/Extension/LimitConsumptionTimeExtensionTest.php b/pkg/enqueue/Tests/Consumption/Extension/LimitConsumptionTimeExtensionTest.php
index 1eaef7874..fa6cb76a1 100644
--- a/pkg/enqueue/Tests/Consumption/Extension/LimitConsumptionTimeExtensionTest.php
+++ b/pkg/enqueue/Tests/Consumption/Extension/LimitConsumptionTimeExtensionTest.php
@@ -10,17 +10,13 @@
use Interop\Queue\Context;
use Interop\Queue\Message;
use Interop\Queue\SubscriptionConsumer;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
class LimitConsumptionTimeExtensionTest extends TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new LimitConsumptionTimeExtension(new \DateTime('+1 day'));
- }
-
public function testOnPreConsumeShouldInterruptExecutionIfConsumptionTimeExceeded()
{
$context = new PreConsume(
@@ -154,7 +150,7 @@ public function testOnPostReceivedShouldNotInterruptExecutionIfConsumptionTimeIs
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
protected function createInteropContextMock(): Context
{
@@ -162,7 +158,7 @@ protected function createInteropContextMock(): Context
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createSubscriptionConsumerMock(): SubscriptionConsumer
{
@@ -170,7 +166,7 @@ private function createSubscriptionConsumerMock(): SubscriptionConsumer
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createLoggerMock(): LoggerInterface
{
diff --git a/pkg/enqueue/Tests/Consumption/Extension/LogExtensionTest.php b/pkg/enqueue/Tests/Consumption/Extension/LogExtensionTest.php
index 8038e5504..01b29f0c0 100644
--- a/pkg/enqueue/Tests/Consumption/Extension/LogExtensionTest.php
+++ b/pkg/enqueue/Tests/Consumption/Extension/LogExtensionTest.php
@@ -20,6 +20,7 @@
use Interop\Queue\Context;
use Interop\Queue\Processor;
use Interop\Queue\Queue;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
@@ -48,11 +49,6 @@ public function testShouldImplementPostMessageReceivedExtensionInterface()
$this->assertClassImplements(PostMessageReceivedExtensionInterface::class, LogExtension::class);
}
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new LogExtension();
- }
-
public function testShouldLogStartOnStart()
{
$logger = $this->createLogger();
@@ -89,7 +85,7 @@ public function testShouldLogMessageReceived()
$logger
->expects($this->once())
->method('debug')
- ->with('Received from {queueName} {body}', [
+ ->with('Received from {queueName}', [
'queueName' => 'aQueue',
'redelivered' => false,
'body' => Stringify::that('aBody'),
@@ -116,7 +112,7 @@ public function testShouldLogMessageProcessedWithStringResult()
->expects($this->once())
->method('log')
->with(LogLevel::INFO,
- 'Processed from {queueName} {body} {result}',
+ 'Processed from {queueName}',
[
'queueName' => 'aQueue',
'body' => Stringify::that('aBody'),
@@ -146,7 +142,7 @@ public function testShouldLogRejectedMessageAsError()
->expects($this->once())
->method('log')
->with(LogLevel::ERROR,
- 'Processed from {queueName} {body} {result}',
+ 'Processed from {queueName}',
[
'queueName' => 'aQueue',
'body' => Stringify::that('aBody'),
@@ -176,7 +172,7 @@ public function testShouldLogMessageProcessedWithResultObject()
->expects($this->once())
->method('log')
->with(LogLevel::INFO,
- 'Processed from {queueName} {body} {result}',
+ 'Processed from {queueName}',
[
'queueName' => 'aQueue',
'body' => Stringify::that('aBody'),
@@ -206,7 +202,7 @@ public function testShouldLogMessageProcessedWithReasonResultObject()
->expects($this->once())
->method('log')
->with(LogLevel::INFO,
- 'Processed from {queueName} {body} {result} {reason}',
+ 'Processed from {queueName}',
[
'queueName' => 'aQueue',
'body' => Stringify::that('aBody'),
@@ -230,7 +226,7 @@ public function testShouldLogMessageProcessedWithReasonResultObject()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createConsumerStub(Queue $queue): Consumer
{
@@ -245,7 +241,7 @@ private function createConsumerStub(Queue $queue): Consumer
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createContextMock(): Context
{
@@ -253,7 +249,7 @@ private function createContextMock(): Context
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createProcessorMock(): Processor
{
@@ -261,7 +257,7 @@ private function createProcessorMock(): Processor
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|LoggerInterface
+ * @return MockObject|LoggerInterface
*/
private function createLogger()
{
diff --git a/pkg/enqueue/Tests/Consumption/Extension/LoggerExtensionTest.php b/pkg/enqueue/Tests/Consumption/Extension/LoggerExtensionTest.php
index 674720e23..666892e0e 100644
--- a/pkg/enqueue/Tests/Consumption/Extension/LoggerExtensionTest.php
+++ b/pkg/enqueue/Tests/Consumption/Extension/LoggerExtensionTest.php
@@ -6,6 +6,7 @@
use Enqueue\Consumption\Extension\LoggerExtension;
use Enqueue\Consumption\InitLoggerExtensionInterface;
use Enqueue\Test\ClassExtensionTrait;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
@@ -19,11 +20,6 @@ public function testShouldImplementInitLoggerExtensionInterface()
$this->assertClassImplements(InitLoggerExtensionInterface::class, LoggerExtension::class);
}
- public function testCouldBeConstructedWithLoggerAsFirstArgument()
- {
- new LoggerExtension($this->createLogger());
- }
-
public function testShouldSetLoggerToContextOnInitLogger()
{
$logger = $this->createLogger();
@@ -46,7 +42,7 @@ public function testShouldAddInfoMessageOnStart()
$logger
->expects($this->once())
->method('debug')
- ->with(sprintf('Change logger from "%s" to "%s"', get_class($logger), get_class($previousLogger)))
+ ->with(sprintf('Change logger from "%s" to "%s"', $logger::class, $previousLogger::class))
;
$extension = new LoggerExtension($logger);
@@ -74,7 +70,7 @@ public function testShouldDoNothingIfSameLoggerInstanceAlreadySet()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|LoggerInterface
+ * @return MockObject|LoggerInterface
*/
protected function createLogger()
{
diff --git a/pkg/enqueue/Tests/Consumption/Extension/NicenessExtensionTest.php b/pkg/enqueue/Tests/Consumption/Extension/NicenessExtensionTest.php
index 5b1834a88..734bc8417 100644
--- a/pkg/enqueue/Tests/Consumption/Extension/NicenessExtensionTest.php
+++ b/pkg/enqueue/Tests/Consumption/Extension/NicenessExtensionTest.php
@@ -5,16 +5,12 @@
use Enqueue\Consumption\Context\Start;
use Enqueue\Consumption\Extension\NicenessExtension;
use Interop\Queue\Context as InteropContext;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
class NicenessExtensionTest extends TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new NicenessExtension(0);
- }
-
public function testShouldThrowExceptionOnInvalidArgument()
{
$this->expectException(\InvalidArgumentException::class);
@@ -33,7 +29,7 @@ public function testShouldThrowWarningOnInvalidArgument()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|InteropContext
+ * @return MockObject|InteropContext
*/
protected function createContextMock(): InteropContext
{
diff --git a/pkg/enqueue/Tests/Consumption/Extension/ReplyExtensionTest.php b/pkg/enqueue/Tests/Consumption/Extension/ReplyExtensionTest.php
index 18e5727fd..cb65816ce 100644
--- a/pkg/enqueue/Tests/Consumption/Extension/ReplyExtensionTest.php
+++ b/pkg/enqueue/Tests/Consumption/Extension/ReplyExtensionTest.php
@@ -12,6 +12,7 @@
use Interop\Queue\Consumer;
use Interop\Queue\Context;
use Interop\Queue\Producer as InteropProducer;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
@@ -24,11 +25,6 @@ public function testShouldImplementPostMessageReceivedExtensionInterface()
$this->assertClassImplements(PostMessageReceivedExtensionInterface::class, ReplyExtension::class);
}
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new ReplyExtension();
- }
-
public function testShouldDoNothingIfReceivedMessageNotHaveReplyToSet()
{
$extension = new ReplyExtension();
@@ -103,7 +99,7 @@ public function testShouldSendReplyMessageToReplyQueueOnPostReceived()
->with($replyQueue, $replyMessage)
;
- /** @var \PHPUnit_Framework_MockObject_MockObject|Context $contextMock */
+ /** @var MockObject|Context $contextMock */
$contextMock = $this->createMock(Context::class);
$contextMock
->expects($this->once())
@@ -129,7 +125,7 @@ public function testShouldSendReplyMessageToReplyQueueOnPostReceived()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
protected function createInteropContextMock(): Context
{
@@ -137,7 +133,7 @@ protected function createInteropContextMock(): Context
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createNeverUsedContextMock(): Context
{
diff --git a/pkg/enqueue/Tests/Consumption/FallbackSubscriptionConsumerTest.php b/pkg/enqueue/Tests/Consumption/FallbackSubscriptionConsumerTest.php
index 588237c92..73fba7bfd 100644
--- a/pkg/enqueue/Tests/Consumption/FallbackSubscriptionConsumerTest.php
+++ b/pkg/enqueue/Tests/Consumption/FallbackSubscriptionConsumerTest.php
@@ -3,6 +3,7 @@
namespace Enqueue\Tests\Consumption;
use Enqueue\Consumption\FallbackSubscriptionConsumer;
+use Enqueue\Test\ReadAttributeTrait;
use Interop\Queue\Consumer;
use Interop\Queue\Message as InteropMessage;
use Interop\Queue\Queue as InteropQueue;
@@ -11,6 +12,8 @@
class FallbackSubscriptionConsumerTest extends TestCase
{
+ use ReadAttributeTrait;
+
public function testShouldImplementSubscriptionConsumerInterface()
{
$rc = new \ReflectionClass(FallbackSubscriptionConsumer::class);
@@ -18,11 +21,6 @@ public function testShouldImplementSubscriptionConsumerInterface()
$this->assertTrue($rc->implementsInterface(SubscriptionConsumer::class));
}
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new FallbackSubscriptionConsumer();
- }
-
public function testShouldInitSubscribersPropertyWithEmptyArray()
{
$subscriptionConsumer = new FallbackSubscriptionConsumer();
@@ -66,6 +64,9 @@ public function testThrowsIfTrySubscribeAnotherConsumerToAlreadySubscribedQueue(
$subscriptionConsumer->subscribe($barConsumer, $barCallback);
}
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldAllowSubscribeSameConsumerAndCallbackSecondTime()
{
$subscriptionConsumer = new FallbackSubscriptionConsumer();
@@ -146,34 +147,18 @@ public function testShouldConsumeMessagesFromTwoQueuesInExpectedOrder()
$fourthMessage = $this->createMessageStub('fourth');
$fifthMessage = $this->createMessageStub('fifth');
- $fooMessages = [null, $firstMessage, null, $secondMessage, $thirdMessage];
-
$fooConsumer = $this->createConsumerStub('foo_queue');
$fooConsumer
->expects($this->any())
->method('receiveNoWait')
- ->willReturnCallback(function () use (&$fooMessages) {
- if (empty($fooMessages)) {
- return null;
- }
-
- return array_shift($fooMessages);
- })
+ ->willReturnOnConsecutiveCalls(null, $firstMessage, null, $secondMessage, $thirdMessage)
;
- $barMessages = [$fourthMessage, null, null, $fifthMessage];
-
$barConsumer = $this->createConsumerStub('bar_queue');
$barConsumer
->expects($this->any())
->method('receiveNoWait')
- ->willReturnCallback(function () use (&$barMessages) {
- if (empty($barMessages)) {
- return null;
- }
-
- return array_shift($barMessages);
- })
+ ->willReturnOnConsecutiveCalls($fourthMessage, null, null, $fifthMessage)
;
$actualOrder = [];
@@ -227,9 +212,9 @@ public function testShouldConsumeTillTimeoutIsReached()
}
/**
- * @param null|mixed $body
+ * @param mixed|null $body
*
- * @return InteropMessage|\PHPUnit_Framework_MockObject_MockObject
+ * @return InteropMessage|\PHPUnit\Framework\MockObject\MockObject
*/
private function createMessageStub($body = null)
{
@@ -244,9 +229,9 @@ private function createMessageStub($body = null)
}
/**
- * @param null|mixed $queueName
+ * @param mixed|null $queueName
*
- * @return Consumer|\PHPUnit_Framework_MockObject_MockObject
+ * @return Consumer|\PHPUnit\Framework\MockObject\MockObject
*/
private function createConsumerStub($queueName = null)
{
diff --git a/pkg/enqueue/Tests/Consumption/QueueConsumerTest.php b/pkg/enqueue/Tests/Consumption/QueueConsumerTest.php
index 9b0111fda..2bcc253e7 100644
--- a/pkg/enqueue/Tests/Consumption/QueueConsumerTest.php
+++ b/pkg/enqueue/Tests/Consumption/QueueConsumerTest.php
@@ -16,10 +16,12 @@
use Enqueue\Consumption\Context\ProcessorException;
use Enqueue\Consumption\Context\Start;
use Enqueue\Consumption\Exception\InvalidArgumentException;
+use Enqueue\Consumption\Extension\ExitStatusExtension;
use Enqueue\Consumption\ExtensionInterface;
use Enqueue\Consumption\QueueConsumer;
use Enqueue\Consumption\Result;
use Enqueue\Null\NullQueue;
+use Enqueue\Test\ReadAttributeTrait;
use Enqueue\Tests\Consumption\Mock\BreakCycleExtension;
use Enqueue\Tests\Consumption\Mock\DummySubscriptionConsumer;
use Interop\Queue\Consumer;
@@ -35,20 +37,7 @@
class QueueConsumerTest extends TestCase
{
- public function testCouldBeConstructedWithAllArguments()
- {
- new QueueConsumer($this->createContextStub(), null, [], null, 0);
- }
-
- public function testCouldBeConstructedWithContextOnly()
- {
- new QueueConsumer($this->createContextStub());
- }
-
- public function testCouldBeConstructedWithContextAndSingleExtension()
- {
- new QueueConsumer($this->createContextStub(), $this->createExtension());
- }
+ use ReadAttributeTrait;
public function testShouldSetEmptyArrayToBoundProcessorsPropertyInConstructor()
{
@@ -176,7 +165,7 @@ public function testShouldAllowBindCallbackToQueueName()
$boundProcessors = $this->readAttribute($consumer, 'boundProcessors');
- $this->assertInternalType('array', $boundProcessors);
+ self::assertIsArray($boundProcessors);
$this->assertCount(1, $boundProcessors);
$this->assertArrayHasKey($queueName, $boundProcessors);
@@ -202,7 +191,6 @@ public function testShouldUseContextSubscriptionConsumerIfSupport()
$contextSubscriptionConsumer
->expects($this->once())
->method('consume')
- ->willReturn(null)
;
$fallbackSubscriptionConsumer = $this->createSubscriptionConsumerMock();
@@ -250,7 +238,6 @@ public function testShouldUseFallbackSubscriptionConsumerIfNotSupported()
$fallbackSubscriptionConsumer
->expects($this->once())
->method('consume')
- ->willReturn(null)
;
$contextMock = $this->createContextWithoutSubscriptionConsumerMock();
@@ -287,7 +274,6 @@ public function testShouldSubscribeToGivenQueueWithExpectedTimeout()
->expects($this->once())
->method('consume')
->with(12345)
- ->willReturn(null)
;
$contextMock = $this->createContextWithoutSubscriptionConsumerMock();
@@ -318,7 +304,6 @@ public function testShouldSubscribeToGivenQueueAndQuitAfterFifthConsumeCycle()
$subscriptionConsumerMock
->expects($this->exactly(5))
->method('consume')
- ->willReturn(null)
;
$contextMock = $this->createContextWithoutSubscriptionConsumerMock();
@@ -1429,8 +1414,31 @@ public function testShouldCallProcessorAsMessageComeAlong()
$this->assertSame($fooConsumerStub, $actualContexts[2]->getConsumer());
}
+ public function testCaptureExitStatus()
+ {
+ $testExitCode = 5;
+
+ $stubExtension = $this->createExtension();
+
+ $stubExtension
+ ->expects($this->once())
+ ->method('onStart')
+ ->with($this->isInstanceOf(Start::class))
+ ->willReturnCallback(function (Start $context) use ($testExitCode) {
+ $context->interruptExecution($testExitCode);
+ })
+ ;
+
+ $exitExtension = new ExitStatusExtension();
+
+ $consumer = new QueueConsumer($this->createContextStub(), $stubExtension);
+ $consumer->consume(new ChainExtension([$exitExtension]));
+
+ $this->assertEquals($testExitCode, $exitExtension->getExitStatus());
+ }
+
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createContextWithoutSubscriptionConsumerMock(): InteropContext
{
@@ -1445,9 +1453,9 @@ private function createContextWithoutSubscriptionConsumerMock(): InteropContext
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|InteropContext
+ * @return \PHPUnit\Framework\MockObject\MockObject|InteropContext
*/
- private function createContextStub(Consumer $consumer = null): InteropContext
+ private function createContextStub(?Consumer $consumer = null): InteropContext
{
$context = $this->createContextWithoutSubscriptionConsumerMock();
$context
@@ -1469,7 +1477,7 @@ private function createContextStub(Consumer $consumer = null): InteropContext
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Processor
+ * @return \PHPUnit\Framework\MockObject\MockObject|Processor
*/
private function createProcessorMock()
{
@@ -1477,7 +1485,7 @@ private function createProcessorMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Processor
+ * @return \PHPUnit\Framework\MockObject\MockObject|Processor
*/
private function createProcessorStub()
{
@@ -1492,7 +1500,7 @@ private function createProcessorStub()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Message
+ * @return \PHPUnit\Framework\MockObject\MockObject|Message
*/
private function createMessageMock(): Message
{
@@ -1500,7 +1508,7 @@ private function createMessageMock(): Message
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ExtensionInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|ExtensionInterface
*/
private function createExtension()
{
@@ -1508,12 +1516,15 @@ private function createExtension()
}
/**
- * @param null|mixed $queue
+ * @param mixed|null $queue
*
- * @return \PHPUnit_Framework_MockObject_MockObject|Consumer
+ * @return \PHPUnit\Framework\MockObject\MockObject|Consumer
*/
private function createConsumerStub($queue = null): Consumer
{
+ if (null === $queue) {
+ $queue = 'queue';
+ }
if (is_string($queue)) {
$queue = new NullQueue($queue);
}
@@ -1529,7 +1540,7 @@ private function createConsumerStub($queue = null): Consumer
}
/**
- * @return SubscriptionConsumer|\PHPUnit_Framework_MockObject_MockObject
+ * @return SubscriptionConsumer|\PHPUnit\Framework\MockObject\MockObject
*/
private function createSubscriptionConsumerMock(): SubscriptionConsumer
{
diff --git a/pkg/enqueue/Tests/DoctrineConnectionFactoryFactoryTest.php b/pkg/enqueue/Tests/DoctrineConnectionFactoryFactoryTest.php
new file mode 100644
index 000000000..14f7b1006
--- /dev/null
+++ b/pkg/enqueue/Tests/DoctrineConnectionFactoryFactoryTest.php
@@ -0,0 +1,71 @@
+registry = $this->prophesize(ManagerRegistry::class);
+ $this->fallbackFactory = $this->prophesize(ConnectionFactoryFactoryInterface::class);
+
+ $this->factory = new DoctrineConnectionFactoryFactory($this->registry->reveal(), $this->fallbackFactory->reveal());
+ }
+
+ public function testCreateWithoutArray()
+ {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('The config must be either array or DSN string.');
+
+ $this->factory->create(true);
+ }
+
+ public function testCreateWithoutDsn()
+ {
+ $this->expectExceptionMessage(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('The config must have dsn key set.');
+
+ $this->factory->create(['foo' => 'bar']);
+ }
+
+ public function testCreateWithDoctrineSchema()
+ {
+ $this->assertInstanceOf(
+ ManagerRegistryConnectionFactory::class,
+ $this->factory->create('doctrine://localhost:3306')
+ );
+ }
+
+ public function testCreateFallback()
+ {
+ $this->fallbackFactory
+ ->create(['dsn' => 'fallback://'])
+ ->shouldBeCalled();
+
+ $this->factory->create(['dsn' => 'fallback://']);
+ }
+}
diff --git a/pkg/enqueue/Tests/Mocks/CustomPrepareBodyClientExtension.php b/pkg/enqueue/Tests/Mocks/CustomPrepareBodyClientExtension.php
index 4d68fa1f3..dd0e1a69e 100644
--- a/pkg/enqueue/Tests/Mocks/CustomPrepareBodyClientExtension.php
+++ b/pkg/enqueue/Tests/Mocks/CustomPrepareBodyClientExtension.php
@@ -2,14 +2,12 @@
namespace Enqueue\Tests\Mocks;
-use Enqueue\Client\EmptyExtensionTrait;
-use Enqueue\Client\ExtensionInterface;
use Enqueue\Client\PreSend;
+use Enqueue\Client\PreSendCommandExtensionInterface;
+use Enqueue\Client\PreSendEventExtensionInterface;
-class CustomPrepareBodyClientExtension implements ExtensionInterface
+class CustomPrepareBodyClientExtension implements PreSendEventExtensionInterface, PreSendCommandExtensionInterface
{
- use EmptyExtensionTrait;
-
public function onPreSendCommand(PreSend $context): void
{
$context->getMessage()->setBody('theCommandBodySerializedByCustomExtension');
diff --git a/pkg/enqueue/Tests/Mocks/JsonSerializableObject.php b/pkg/enqueue/Tests/Mocks/JsonSerializableObject.php
index 5b74106dc..84885c316 100644
--- a/pkg/enqueue/Tests/Mocks/JsonSerializableObject.php
+++ b/pkg/enqueue/Tests/Mocks/JsonSerializableObject.php
@@ -4,7 +4,8 @@
class JsonSerializableObject implements \JsonSerializable
{
- public function jsonSerialize()
+ #[\ReturnTypeWillChange]
+ public function jsonSerialize(): array
{
return ['foo' => 'fooVal'];
}
diff --git a/pkg/enqueue/Tests/ResourcesTest.php b/pkg/enqueue/Tests/ResourcesTest.php
index 52bd13f9f..ec713fd03 100644
--- a/pkg/enqueue/Tests/ResourcesTest.php
+++ b/pkg/enqueue/Tests/ResourcesTest.php
@@ -4,6 +4,7 @@
use Enqueue\Redis\RedisConnectionFactory;
use Enqueue\Resources;
+use Enqueue\Wamp\WampConnectionFactory;
use Interop\Queue\ConnectionFactory;
use PHPUnit\Framework\TestCase;
@@ -27,12 +28,12 @@ public function testShouldGetAvailableConnectionsInExpectedFormat()
{
$availableConnections = Resources::getAvailableConnections();
- $this->assertInternalType('array', $availableConnections);
+ self::assertIsArray($availableConnections);
$this->assertArrayHasKey(RedisConnectionFactory::class, $availableConnections);
$connectionInfo = $availableConnections[RedisConnectionFactory::class];
$this->assertArrayHasKey('schemes', $connectionInfo);
- $this->assertSame(['redis'], $connectionInfo['schemes']);
+ $this->assertSame(['redis', 'rediss'], $connectionInfo['schemes']);
$this->assertArrayHasKey('supportedSchemeExtensions', $connectionInfo);
$this->assertSame(['predis', 'phpredis'], $connectionInfo['supportedSchemeExtensions']);
@@ -45,12 +46,12 @@ public function testShouldGetKnownConnectionsInExpectedFormat()
{
$availableConnections = Resources::getKnownConnections();
- $this->assertInternalType('array', $availableConnections);
+ self::assertIsArray($availableConnections);
$this->assertArrayHasKey(RedisConnectionFactory::class, $availableConnections);
$connectionInfo = $availableConnections[RedisConnectionFactory::class];
$this->assertArrayHasKey('schemes', $connectionInfo);
- $this->assertSame(['redis'], $connectionInfo['schemes']);
+ $this->assertSame(['redis', 'rediss'], $connectionInfo['schemes']);
$this->assertArrayHasKey('supportedSchemeExtensions', $connectionInfo);
$this->assertSame(['predis', 'phpredis'], $connectionInfo['supportedSchemeExtensions']);
@@ -92,12 +93,12 @@ public function testShouldAllowRegisterConnectionThatIsNotInstalled()
Resources::addConnection('theConnectionClass', ['foo'], [], 'foo');
$knownConnections = Resources::getKnownConnections();
- $this->assertInternalType('array', $knownConnections);
+ self::assertIsArray($knownConnections);
$this->assertArrayHasKey('theConnectionClass', $knownConnections);
$availableConnections = Resources::getAvailableConnections();
- $this->assertInternalType('array', $availableConnections);
+ self::assertIsArray($availableConnections);
$this->assertArrayNotHasKey('theConnectionClass', $availableConnections);
}
@@ -114,7 +115,7 @@ public function testShouldAllowGetPreviouslyRegisteredConnection()
$availableConnections = Resources::getAvailableConnections();
- $this->assertInternalType('array', $availableConnections);
+ self::assertIsArray($availableConnections);
$this->assertArrayHasKey($connectionClass, $availableConnections);
$connectionInfo = $availableConnections[$connectionClass];
@@ -127,4 +128,22 @@ public function testShouldAllowGetPreviouslyRegisteredConnection()
$this->assertArrayHasKey('package', $connectionInfo);
$this->assertSame('foo/bar', $connectionInfo['package']);
}
+
+ public function testShouldHaveRegisteredWampConfiguration()
+ {
+ $availableConnections = Resources::getKnownConnections();
+
+ self::assertIsArray($availableConnections);
+ $this->assertArrayHasKey(WampConnectionFactory::class, $availableConnections);
+
+ $connectionInfo = $availableConnections[WampConnectionFactory::class];
+ $this->assertArrayHasKey('schemes', $connectionInfo);
+ $this->assertSame(['wamp', 'ws'], $connectionInfo['schemes']);
+
+ $this->assertArrayHasKey('supportedSchemeExtensions', $connectionInfo);
+ $this->assertSame([], $connectionInfo['supportedSchemeExtensions']);
+
+ $this->assertArrayHasKey('package', $connectionInfo);
+ $this->assertSame('enqueue/wamp', $connectionInfo['package']);
+ }
}
diff --git a/pkg/enqueue/Tests/Router/RouteRecipientListProcessorTest.php b/pkg/enqueue/Tests/Router/RouteRecipientListProcessorTest.php
index 38e05806e..ae878fc53 100644
--- a/pkg/enqueue/Tests/Router/RouteRecipientListProcessorTest.php
+++ b/pkg/enqueue/Tests/Router/RouteRecipientListProcessorTest.php
@@ -23,11 +23,6 @@ public function testShouldImplementProcessorInterface()
$this->assertClassImplements(Processor::class, RouteRecipientListProcessor::class);
}
- public function testCouldBeConstructedWithRouterAsFirstArgument()
- {
- new RouteRecipientListProcessor($this->createRecipientListRouterMock());
- }
-
public function testShouldProduceRecipientsMessagesAndAckOriginalMessage()
{
$fooRecipient = new Recipient(new NullQueue('aName'), new NullMessage());
@@ -70,7 +65,7 @@ public function testShouldProduceRecipientsMessagesAndAckOriginalMessage()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|InteropProducer
+ * @return \PHPUnit\Framework\MockObject\MockObject|InteropProducer
*/
protected function createProducerMock()
{
@@ -78,7 +73,7 @@ protected function createProducerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Context
+ * @return \PHPUnit\Framework\MockObject\MockObject|Context
*/
protected function createContextMock()
{
@@ -86,7 +81,7 @@ protected function createContextMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|RecipientListRouterInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|RecipientListRouterInterface
*/
protected function createRecipientListRouterMock()
{
diff --git a/pkg/enqueue/Tests/Rpc/PromiseTest.php b/pkg/enqueue/Tests/Rpc/PromiseTest.php
index 2755ef469..6762149ef 100644
--- a/pkg/enqueue/Tests/Rpc/PromiseTest.php
+++ b/pkg/enqueue/Tests/Rpc/PromiseTest.php
@@ -50,10 +50,10 @@ public function testOnReceiveShouldCallReceiveCallBackWithTimeout()
$receiveInvoked = false;
$receivePromise = null;
$receiveTimeout = null;
- $receivecb = function ($promise, $timout) use (&$receiveInvoked, &$receivePromise, &$receiveTimeout) {
+ $receivecb = function ($promise, $timeout) use (&$receiveInvoked, &$receivePromise, &$receiveTimeout) {
$receiveInvoked = true;
$receivePromise = $promise;
- $receiveTimeout = $timout;
+ $receiveTimeout = $timeout;
};
$promise = new Promise($receivecb, function () {}, function () {});
diff --git a/pkg/enqueue/Tests/Rpc/RpcClientTest.php b/pkg/enqueue/Tests/Rpc/RpcClientTest.php
index 78f72bbe5..db4813c88 100644
--- a/pkg/enqueue/Tests/Rpc/RpcClientTest.php
+++ b/pkg/enqueue/Tests/Rpc/RpcClientTest.php
@@ -10,15 +10,11 @@
use Interop\Queue\Consumer;
use Interop\Queue\Context;
use Interop\Queue\Producer as InteropProducer;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class RpcClientTest extends TestCase
{
- public function testCouldBeConstructedWithContextAsFirstArgument()
- {
- new RpcClient($this->createContextMock());
- }
-
public function testShouldSetReplyToIfNotSet()
{
$context = new NullContext();
@@ -329,7 +325,7 @@ public function testShouldDoSyncCall()
}
/**
- * @return Context|\PHPUnit_Framework_MockObject_MockObject|InteropProducer
+ * @return Context|MockObject|InteropProducer
*/
private function createInteropProducerMock()
{
@@ -337,7 +333,7 @@ private function createInteropProducerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Consumer
+ * @return MockObject|Consumer
*/
private function createConsumerMock()
{
@@ -345,7 +341,7 @@ private function createConsumerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Context
+ * @return MockObject|Context
*/
private function createContextMock()
{
diff --git a/pkg/enqueue/Tests/Symfony/Client/ConsumeCommandTest.php b/pkg/enqueue/Tests/Symfony/Client/ConsumeCommandTest.php
index e57696a02..3758ca96a 100644
--- a/pkg/enqueue/Tests/Symfony/Client/ConsumeCommandTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/ConsumeCommandTest.php
@@ -8,13 +8,21 @@
use Enqueue\Client\Route;
use Enqueue\Client\RouteCollection;
use Enqueue\Consumption\ChainExtension;
+use Enqueue\Consumption\Context\Start;
+use Enqueue\Consumption\ExtensionInterface;
+use Enqueue\Consumption\QueueConsumer;
use Enqueue\Consumption\QueueConsumerInterface;
use Enqueue\Container\Container;
use Enqueue\Null\NullQueue;
use Enqueue\Symfony\Client\ConsumeCommand;
use Enqueue\Test\ClassExtensionTrait;
+use Interop\Queue\Consumer;
+use Interop\Queue\Context as InteropContext;
+use Interop\Queue\Exception\SubscriptionConsumerNotSupportedException;
+use Interop\Queue\Queue;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;
@@ -32,21 +40,27 @@ public function testShouldNotBeFinal()
$this->assertClassNotFinal(ConsumeCommand::class);
}
- public function testCouldBeConstructedWithRequiredAttributes()
+ public function testShouldHaveAsCommandAttributeWithCommandName()
{
- new ConsumeCommand($this->createMock(ContainerInterface::class));
- }
+ $commandClass = ConsumeCommand::class;
- public function testShouldHaveCommandName()
- {
- $command = new ConsumeCommand($this->createMock(ContainerInterface::class));
+ $reflectionClass = new \ReflectionClass($commandClass);
+
+ $attributes = $reflectionClass->getAttributes(AsCommand::class);
+
+ $this->assertNotEmpty($attributes, 'The command does not have the AsCommand attribute.');
+
+ // Get the first attribute instance (assuming there is only one AsCommand attribute)
+ $asCommandAttribute = $attributes[0];
- $this->assertEquals('enqueue:consume', $command->getName());
+ // Verify the 'name' parameter value
+ $attributeInstance = $asCommandAttribute->newInstance();
+ $this->assertEquals('enqueue:consume', $attributeInstance->name, 'The command name is not set correctly in the AsCommand attribute.');
}
public function testShouldHaveExpectedOptions()
{
- $command = new ConsumeCommand($this->createMock(ContainerInterface::class));
+ $command = new ConsumeCommand($this->createMock(ContainerInterface::class), 'default');
$options = $command->getDefinition()->getOptions();
@@ -64,7 +78,7 @@ public function testShouldHaveExpectedOptions()
public function testShouldHaveExpectedAttributes()
{
- $command = new ConsumeCommand($this->createMock(ContainerInterface::class));
+ $command = new ConsumeCommand($this->createMock(ContainerInterface::class), 'default');
$arguments = $command->getDefinition()->getArguments();
@@ -96,7 +110,7 @@ public function testShouldBindDefaultQueueOnly()
$driver
->expects($this->once())
->method('createQueue')
- ->with('default')
+ ->with('default', true)
->willReturn($queue)
;
@@ -104,7 +118,7 @@ public function testShouldBindDefaultQueueOnly()
'enqueue.client.default.queue_consumer' => $consumer,
'enqueue.client.default.driver' => $driver,
'enqueue.client.default.delegate_processor' => $processor,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([]);
@@ -153,7 +167,7 @@ public function testShouldUseRequestedClient()
$fooDriver
->expects($this->once())
->method('createQueue')
- ->with('default')
+ ->with('default', true)
->willReturn($queue)
;
@@ -164,7 +178,7 @@ public function testShouldUseRequestedClient()
'enqueue.client.foo.queue_consumer' => $fooConsumer,
'enqueue.client.foo.driver' => $fooDriver,
'enqueue.client.foo.delegate_processor' => $fooProcessor,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
@@ -198,7 +212,7 @@ public function testThrowIfNotDefinedClientRequested()
'enqueue.client.default.queue_consumer' => $consumer,
'enqueue.client.default.driver' => $driver,
'enqueue.client.default.delegate_processor' => $processor,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -235,7 +249,7 @@ public function testShouldBindDefaultQueueIfRouteUseDifferentQueue()
$driver
->expects($this->once())
->method('createQueue')
- ->with('default')
+ ->with('default', true)
->willReturn($queue)
;
@@ -243,7 +257,7 @@ public function testShouldBindDefaultQueueIfRouteUseDifferentQueue()
'enqueue.client.default.queue_consumer' => $consumer,
'enqueue.client.default.driver' => $driver,
'enqueue.client.default.delegate_processor' => $processor,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([]);
@@ -264,13 +278,13 @@ public function testShouldBindCustomExecuteConsumptionAndUseCustomClientDestinat
$driver
->expects($this->at(3))
->method('createQueue')
- ->with('default')
+ ->with('default', true)
->willReturn($defaultQueue)
;
$driver
->expects($this->at(4))
->method('createQueue')
- ->with('custom')
+ ->with('custom', true)
->willReturn($customQueue)
;
@@ -295,7 +309,7 @@ public function testShouldBindCustomExecuteConsumptionAndUseCustomClientDestinat
'enqueue.client.default.queue_consumer' => $consumer,
'enqueue.client.default.driver' => $driver,
'enqueue.client.default.delegate_processor' => $processor,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([]);
@@ -307,6 +321,7 @@ public function testShouldBindUserProvidedQueues()
$routeCollection = new RouteCollection([
new Route('topic', Route::TOPIC, 'processor', ['queue' => 'custom']),
+ new Route('topic', Route::TOPIC, 'processor', ['queue' => 'non-default-queue']),
]);
$processor = $this->createDelegateProcessorMock();
@@ -315,7 +330,7 @@ public function testShouldBindUserProvidedQueues()
$driver
->expects($this->once())
->method('createQueue')
- ->with('non-default-queue')
+ ->with('non-default-queue', true)
->willReturn($queue)
;
@@ -335,7 +350,7 @@ public function testShouldBindUserProvidedQueues()
'enqueue.client.default.queue_consumer' => $consumer,
'enqueue.client.default.driver' => $driver,
'enqueue.client.default.delegate_processor' => $processor,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
@@ -343,6 +358,48 @@ public function testShouldBindUserProvidedQueues()
]);
}
+ public function testShouldBindNotPrefixedQueue()
+ {
+ $queue = new NullQueue('');
+
+ $routeCollection = new RouteCollection([
+ new Route('topic', Route::TOPIC, 'processor', ['queue' => 'non-prefixed-queue', 'prefix_queue' => false]),
+ ]);
+
+ $processor = $this->createDelegateProcessorMock();
+
+ $driver = $this->createDriverStub($routeCollection);
+ $driver
+ ->expects($this->once())
+ ->method('createQueue')
+ ->with('non-prefixed-queue', false)
+ ->willReturn($queue)
+ ;
+
+ $consumer = $this->createQueueConsumerMock();
+ $consumer
+ ->expects($this->once())
+ ->method('bind')
+ ->with($this->identicalTo($queue), $this->identicalTo($processor))
+ ;
+ $consumer
+ ->expects($this->once())
+ ->method('consume')
+ ->with($this->isInstanceOf(ChainExtension::class))
+ ;
+
+ $command = new ConsumeCommand(new Container([
+ 'enqueue.client.default.queue_consumer' => $consumer,
+ 'enqueue.client.default.driver' => $driver,
+ 'enqueue.client.default.delegate_processor' => $processor,
+ ]), 'default');
+
+ $tester = new CommandTester($command);
+ $tester->execute([
+ 'client-queue-names' => ['non-prefixed-queue'],
+ ]);
+ }
+
public function testShouldBindQueuesOnlyOnce()
{
$defaultQueue = new NullQueue('');
@@ -360,12 +417,12 @@ public function testShouldBindQueuesOnlyOnce()
$driver
->expects($this->at(3))
->method('createQueue')
- ->with('default')
+ ->with('default', true)
->willReturn($defaultQueue)
;
$driver
->expects($this->at(4))
- ->method('createQueue')
+ ->method('createQueue', true)
->with('custom')
->willReturn($customQueue)
;
@@ -391,7 +448,48 @@ public function testShouldBindQueuesOnlyOnce()
'enqueue.client.default.queue_consumer' => $consumer,
'enqueue.client.default.driver' => $driver,
'enqueue.client.default.delegate_processor' => $processor,
- ]));
+ ]), 'default');
+
+ $tester = new CommandTester($command);
+ $tester->execute([]);
+ }
+
+ public function testShouldNotBindExternalRoutes()
+ {
+ $defaultQueue = new NullQueue('');
+
+ $routeCollection = new RouteCollection([
+ new Route('barTopic', Route::TOPIC, 'processor', ['queue' => null]),
+ new Route('fooTopic', Route::TOPIC, 'processor', ['queue' => 'external_queue', 'external' => true]),
+ ]);
+
+ $processor = $this->createDelegateProcessorMock();
+
+ $driver = $this->createDriverStub($routeCollection);
+ $driver
+ ->expects($this->exactly(1))
+ ->method('createQueue')
+ ->with('default', true)
+ ->willReturn($defaultQueue)
+ ;
+
+ $consumer = $this->createQueueConsumerMock();
+ $consumer
+ ->expects($this->exactly(1))
+ ->method('bind')
+ ->with($this->identicalTo($defaultQueue), $this->identicalTo($processor))
+ ;
+ $consumer
+ ->expects($this->at(1))
+ ->method('consume')
+ ->with($this->isInstanceOf(ChainExtension::class))
+ ;
+
+ $command = new ConsumeCommand(new Container([
+ 'enqueue.client.default.queue_consumer' => $consumer,
+ 'enqueue.client.default.driver' => $driver,
+ 'enqueue.client.default.delegate_processor' => $processor,
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([]);
@@ -423,19 +521,19 @@ public function testShouldSkipQueueConsumptionAndUseCustomClientDestinationName(
$driver = $this->createDriverStub($routeCollection);
$driver
->expects($this->at(3))
- ->method('createQueue')
+ ->method('createQueue', true)
->with('default')
->willReturn($queue)
;
$driver
->expects($this->at(4))
- ->method('createQueue')
+ ->method('createQueue', true)
->with('fooQueue')
->willReturn($queue)
;
$driver
->expects($this->at(5))
- ->method('createQueue')
+ ->method('createQueue', true)
->with('ololoQueue')
->willReturn($queue)
;
@@ -444,7 +542,7 @@ public function testShouldSkipQueueConsumptionAndUseCustomClientDestinationName(
'enqueue.client.default.queue_consumer' => $consumer,
'enqueue.client.default.driver' => $driver,
'enqueue.client.default.delegate_processor' => $processor,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
@@ -452,8 +550,51 @@ public function testShouldSkipQueueConsumptionAndUseCustomClientDestinationName(
]);
}
+ public function testShouldReturnExitStatusIfSet()
+ {
+ $testExitCode = 678;
+
+ $stubExtension = $this->createExtension();
+
+ $stubExtension
+ ->expects($this->once())
+ ->method('onStart')
+ ->with($this->isInstanceOf(Start::class))
+ ->willReturnCallback(function (Start $context) use ($testExitCode) {
+ $context->interruptExecution($testExitCode);
+ })
+ ;
+
+ $defaultQueue = new NullQueue('default');
+
+ $routeCollection = new RouteCollection([]);
+
+ $processor = $this->createDelegateProcessorMock();
+
+ $driver = $this->createDriverStub($routeCollection);
+ $driver
+ ->expects($this->exactly(1))
+ ->method('createQueue')
+ ->with('default', true)
+ ->willReturn($defaultQueue)
+ ;
+
+ $consumer = new QueueConsumer($this->createContextStub(), $stubExtension);
+
+ $command = new ConsumeCommand(new Container([
+ 'enqueue.client.default.queue_consumer' => $consumer,
+ 'enqueue.client.default.driver' => $driver,
+ 'enqueue.client.default.delegate_processor' => $processor,
+ ]), 'default');
+
+ $tester = new CommandTester($command);
+ $tester->execute([]);
+
+ $this->assertEquals($testExitCode, $tester->getStatusCode());
+ }
+
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|DelegateProcessor
+ * @return \PHPUnit\Framework\MockObject\MockObject|DelegateProcessor
*/
private function createDelegateProcessorMock()
{
@@ -461,7 +602,7 @@ private function createDelegateProcessorMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|QueueConsumerInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|QueueConsumerInterface
*/
private function createQueueConsumerMock()
{
@@ -469,15 +610,15 @@ private function createQueueConsumerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|DriverInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|DriverInterface
*/
- private function createDriverStub(RouteCollection $routeCollection = null): DriverInterface
+ private function createDriverStub(?RouteCollection $routeCollection = null): DriverInterface
{
$driverMock = $this->createMock(DriverInterface::class);
$driverMock
->expects($this->any())
->method('getRouteCollection')
- ->willReturn($routeCollection)
+ ->willReturn($routeCollection ?? new RouteCollection([]))
;
$driverMock
@@ -488,4 +629,75 @@ private function createDriverStub(RouteCollection $routeCollection = null): Driv
return $driverMock;
}
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject
+ */
+ private function createContextWithoutSubscriptionConsumerMock(): InteropContext
+ {
+ $contextMock = $this->createMock(InteropContext::class);
+ $contextMock
+ ->expects($this->any())
+ ->method('createSubscriptionConsumer')
+ ->willThrowException(SubscriptionConsumerNotSupportedException::providerDoestNotSupportIt())
+ ;
+
+ return $contextMock;
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|InteropContext
+ */
+ private function createContextStub(?Consumer $consumer = null): InteropContext
+ {
+ $context = $this->createContextWithoutSubscriptionConsumerMock();
+ $context
+ ->expects($this->any())
+ ->method('createQueue')
+ ->willReturnCallback(function (string $queueName) {
+ return new NullQueue($queueName);
+ })
+ ;
+ $context
+ ->expects($this->any())
+ ->method('createConsumer')
+ ->willReturnCallback(function (Queue $queue) use ($consumer) {
+ return $consumer ?: $this->createConsumerStub($queue);
+ })
+ ;
+
+ return $context;
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|ExtensionInterface
+ */
+ private function createExtension()
+ {
+ return $this->createMock(ExtensionInterface::class);
+ }
+
+ /**
+ * @param mixed|null $queue
+ *
+ * @return \PHPUnit\Framework\MockObject\MockObject|Consumer
+ */
+ private function createConsumerStub($queue = null): Consumer
+ {
+ if (null === $queue) {
+ $queue = 'queue';
+ }
+ if (is_string($queue)) {
+ $queue = new NullQueue($queue);
+ }
+
+ $consumerMock = $this->createMock(Consumer::class);
+ $consumerMock
+ ->expects($this->any())
+ ->method('getQueue')
+ ->willReturn($queue)
+ ;
+
+ return $consumerMock;
+ }
}
diff --git a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/AnalyzeRouteCollectionPassTest.php b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/AnalyzeRouteCollectionPassTest.php
index c2f7386af..568de6488 100644
--- a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/AnalyzeRouteCollectionPassTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/AnalyzeRouteCollectionPassTest.php
@@ -23,29 +23,31 @@ public function testShouldBeFinal()
$this->assertClassFinal(AnalyzeRouteCollectionPass::class);
}
- public function testCouldBeConstructedWithName()
+ public function testThrowIfEnqueueClientsParameterNotSet()
{
- $pass = new AnalyzeRouteCollectionPass('aName');
+ $pass = new AnalyzeRouteCollectionPass();
- $this->assertAttributeSame('aName', 'name', $pass);
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The "enqueue.clients" parameter must be set.');
+ $pass->process(new ContainerBuilder());
}
- public function testThrowIfNameEmptyOnConstruct()
+ public function testThrowsIfNoRouteCollectionServiceFoundForConfiguredTransport()
{
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The name could not be empty.');
- new AnalyzeRouteCollectionPass('');
- }
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo', 'bar']);
- public function testShouldDoNothingIfRouteCollectionServiceIsNotRegistered()
- {
- $pass = new AnalyzeRouteCollectionPass('aName');
- $pass->process(new ContainerBuilder());
+ $pass = new AnalyzeRouteCollectionPass();
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Service "enqueue.client.foo.route_collection" not found');
+ $pass->process($container);
}
public function testThrowIfExclusiveCommandProcessorOnDefaultQueue()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['aName']);
$container->register('enqueue.client.aName.route_collection')->addArgument([
(new Route(
'aCommand',
@@ -57,7 +59,7 @@ public function testThrowIfExclusiveCommandProcessorOnDefaultQueue()
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The command "aCommand" processor "aBarProcessor" is exclusive but queue is not specified. Exclusive processors could not be run on a default queue.');
- $pass = new AnalyzeRouteCollectionPass('aName');
+ $pass = new AnalyzeRouteCollectionPass();
$pass->process($container);
}
@@ -65,6 +67,7 @@ public function testThrowIfExclusiveCommandProcessorOnDefaultQueue()
public function testThrowIfTwoExclusiveCommandProcessorsWorkOnSamePrefixedQueue()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['aName']);
$container->register('enqueue.client.aName.route_collection')->addArgument([
(new Route(
'aFooCommand',
@@ -83,7 +86,7 @@ public function testThrowIfTwoExclusiveCommandProcessorsWorkOnSamePrefixedQueue(
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The command "aBarCommand" processor "aBarProcessor" is exclusive. The queue "aQueue" already has another exclusive command processor "aFooProcessor" bound to it.');
- $pass = new AnalyzeRouteCollectionPass('aName');
+ $pass = new AnalyzeRouteCollectionPass();
$pass->process($container);
}
@@ -91,6 +94,7 @@ public function testThrowIfTwoExclusiveCommandProcessorsWorkOnSamePrefixedQueue(
public function testThrowIfTwoExclusiveCommandProcessorsWorkOnSameQueue()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['aName']);
$container->register('enqueue.client.aName.route_collection')->addArgument([
(new Route(
'aFooCommand',
@@ -109,32 +113,55 @@ public function testThrowIfTwoExclusiveCommandProcessorsWorkOnSameQueue()
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The command "aBarCommand" processor "aBarProcessor" is exclusive. The queue "aQueue" already has another exclusive command processor "aFooProcessor" bound to it.');
- $pass = new AnalyzeRouteCollectionPass('aName');
+ $pass = new AnalyzeRouteCollectionPass();
$pass->process($container);
}
- public function testShouldNotThrowIfTwoExclusiveCommandProcessorsWorkOnQueueWithSameNameButOnePrefixed()
+ public function testThrowIfThereAreTwoQueuesWithSameNameAndOneNotPrefixed()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['aName']);
$container->register('enqueue.client.aName.route_collection')->addArgument([
(new Route(
'aFooCommand',
Route::COMMAND,
'aFooProcessor',
- ['exclusive' => true, 'queue' => 'aQueue', 'prefix_queue' => false]
+ ['queue' => 'foo', 'prefix_queue' => false]
))->toArray(),
(new Route(
'aBarCommand',
Route::COMMAND,
'aBarProcessor',
- ['exclusive' => true, 'queue' => 'aQueue', 'prefix_queue' => true]
+ ['queue' => 'foo', 'prefix_queue' => true]
))->toArray(),
]);
- $pass = new AnalyzeRouteCollectionPass('aName');
+ $pass = new AnalyzeRouteCollectionPass();
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('There are prefixed and not prefixed queue with the same name "foo". This is not allowed.');
+ $pass->process($container);
+ }
+
+ public function testThrowIfDefaultQueueNotPrefixed()
+ {
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['aName']);
+ $container->register('enqueue.client.aName.route_collection')->addArgument([
+ (new Route(
+ 'aFooCommand',
+ Route::COMMAND,
+ 'aFooProcessor',
+ ['queue' => null, 'prefix_queue' => false]
+ ))->toArray(),
+ ]);
+
+ $pass = new AnalyzeRouteCollectionPass();
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The default queue must be prefixed.');
$pass->process($container);
}
}
diff --git a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildClientExtensionsPassTest.php b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildClientExtensionsPassTest.php
index 46f549167..753790369 100644
--- a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildClientExtensionsPassTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildClientExtensionsPassTest.php
@@ -25,28 +25,25 @@ public function testShouldBeFinal()
$this->assertClassFinal(BuildClientExtensionsPass::class);
}
- public function testCouldBeConstructedWithName()
+ public function testThrowIfEnqueueClientsParameterNotSet()
{
- $pass = new BuildClientExtensionsPass('aName');
+ $pass = new BuildClientExtensionsPass();
- $this->assertAttributeSame('aName', 'name', $pass);
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The "enqueue.clients" parameter must be set.');
+ $pass->process(new ContainerBuilder());
}
- public function testThrowIfNameEmptyOnConstruct()
- {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The name could not be empty.');
- new BuildClientExtensionsPass('');
- }
-
- public function testShouldDoNothingIfExtensionsServiceIsNotRegistered()
+ public function testThrowsIfNoClientExtensionsServiceFoundForConfiguredTransport()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo', 'bar']);
+ $container->setParameter('enqueue.default_client', 'foo');
- //guard
- $this->assertFalse($container->hasDefinition('enqueue.client.aName.client_extensions'));
+ $pass = new BuildClientExtensionsPass();
- $pass = new BuildClientExtensionsPass('aName');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Service "enqueue.client.foo.client_extensions" not found');
$pass->process($container);
}
@@ -56,6 +53,8 @@ public function testShouldRegisterClientExtension()
$extensions->addArgument([]);
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['aName']);
+ $container->setParameter('enqueue.default_client', 'foo');
$container->setDefinition('enqueue.client.aName.client_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
@@ -65,10 +64,10 @@ public function testShouldRegisterClientExtension()
->addTag('enqueue.client_extension', ['client' => 'aName'])
;
- $pass = new BuildClientExtensionsPass('aName');
+ $pass = new BuildClientExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
new Reference('aBarExtension'),
@@ -81,6 +80,8 @@ public function testShouldIgnoreOtherClientExtensions()
$extensions->addArgument([]);
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['aName']);
+ $container->setParameter('enqueue.default_client', 'foo');
$container->setDefinition('enqueue.client.aName.client_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
@@ -90,10 +91,10 @@ public function testShouldIgnoreOtherClientExtensions()
->addTag('enqueue.client_extension', ['client' => 'anotherName'])
;
- $pass = new BuildClientExtensionsPass('aName');
+ $pass = new BuildClientExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
], $extensions->getArgument(0));
@@ -105,6 +106,8 @@ public function testShouldAddExtensionIfClientAll()
$extensions->addArgument([]);
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['aName']);
+ $container->setParameter('enqueue.default_client', 'foo');
$container->setDefinition('enqueue.client.aName.client_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
@@ -114,10 +117,10 @@ public function testShouldAddExtensionIfClientAll()
->addTag('enqueue.client_extension', ['client' => 'anotherName'])
;
- $pass = new BuildClientExtensionsPass('aName');
+ $pass = new BuildClientExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
], $extensions->getArgument(0));
@@ -129,7 +132,9 @@ public function testShouldTreatTagsWithoutClientAsDefaultClient()
$extensions->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.client_extensions', $extensions);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.client_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
->addTag('enqueue.client_extension')
@@ -138,10 +143,10 @@ public function testShouldTreatTagsWithoutClientAsDefaultClient()
->addTag('enqueue.client_extension')
;
- $pass = new BuildClientExtensionsPass('default');
+ $pass = new BuildClientExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
new Reference('aBarExtension'),
@@ -151,10 +156,12 @@ public function testShouldTreatTagsWithoutClientAsDefaultClient()
public function testShouldOrderExtensionsByPriority()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
$extensions = new Definition();
$extensions->addArgument([]);
- $container->setDefinition('enqueue.client.default.client_extensions', $extensions);
+ $container->setDefinition('enqueue.client.foo.client_extensions', $extensions);
$extension = new Definition();
$extension->addTag('enqueue.client_extension', ['priority' => 6]);
@@ -168,7 +175,7 @@ public function testShouldOrderExtensionsByPriority()
$extension->addTag('enqueue.client_extension', ['priority' => 2]);
$container->setDefinition('baz_extension', $extension);
- $pass = new BuildClientExtensionsPass('default');
+ $pass = new BuildClientExtensionsPass();
$pass->process($container);
$orderedExtensions = $extensions->getArgument(0);
@@ -182,10 +189,12 @@ public function testShouldOrderExtensionsByPriority()
public function testShouldAssumePriorityZeroIfPriorityIsNotSet()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
$extensions = new Definition();
$extensions->addArgument([]);
- $container->setDefinition('enqueue.client.default.client_extensions', $extensions);
+ $container->setDefinition('enqueue.client.foo.client_extensions', $extensions);
$extension = new Definition();
$extension->addTag('enqueue.client_extension');
@@ -199,7 +208,7 @@ public function testShouldAssumePriorityZeroIfPriorityIsNotSet()
$extension->addTag('enqueue.client_extension', ['priority' => -1]);
$container->setDefinition('baz_extension', $extension);
- $pass = new BuildClientExtensionsPass('default');
+ $pass = new BuildClientExtensionsPass();
$pass->process($container);
$orderedExtensions = $extensions->getArgument(0);
@@ -219,7 +228,9 @@ public function testShouldMergeWithAddedPreviously()
]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.aName.client_extensions', $extensions);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.client_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
->addTag('enqueue.client_extension')
@@ -228,13 +239,45 @@ public function testShouldMergeWithAddedPreviously()
->addTag('enqueue.client_extension')
;
- $pass = new BuildClientExtensionsPass('aName');
+ $pass = new BuildClientExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
+ $this->assertCount(4, $extensions->getArgument(0));
+ }
+
+ public function testShouldRegisterProcessorWithMatchedNameToCorrespondingExtensions()
+ {
+ $fooExtensions = new Definition();
+ $fooExtensions->addArgument([]);
+
+ $barExtensions = new Definition();
+ $barExtensions->addArgument([]);
+
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo', 'bar']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.client_extensions', $fooExtensions);
+ $container->setDefinition('enqueue.client.bar.client_extensions', $barExtensions);
+
+ $container->register('aFooExtension', ExtensionInterface::class)
+ ->addTag('enqueue.client_extension', ['client' => 'foo'])
+ ;
+ $container->register('aBarExtension', ExtensionInterface::class)
+ ->addTag('enqueue.client_extension', ['client' => 'bar'])
+ ;
+
+ $pass = new BuildClientExtensionsPass();
+ $pass->process($container);
+
+ self::assertIsArray($fooExtensions->getArgument(0));
$this->assertEquals([
- 'aBarExtension' => 'aBarServiceIdAddedPreviously',
- 'aOloloExtension' => 'aOloloServiceIdAddedPreviously',
- ], $extensions->getArgument(0));
+ new Reference('aFooExtension'),
+ ], $fooExtensions->getArgument(0));
+
+ self::assertIsArray($barExtensions->getArgument(0));
+ $this->assertEquals([
+ new Reference('aBarExtension'),
+ ], $barExtensions->getArgument(0));
}
}
diff --git a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildCommandSubscriberRoutesPassTest.php b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildCommandSubscriberRoutesPassTest.php
index 9d375227c..e1ed297c6 100644
--- a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildCommandSubscriberRoutesPassTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildCommandSubscriberRoutesPassTest.php
@@ -29,29 +29,33 @@ public function testShouldBeFinal()
$this->assertClassFinal(BuildCommandSubscriberRoutesPass::class);
}
- public function testCouldBeConstructedWithName()
+ public function testThrowIfEnqueueClientsParameterNotSet()
{
- $pass = new BuildCommandSubscriberRoutesPass('aName');
+ $pass = new BuildCommandSubscriberRoutesPass();
- $this->assertAttributeSame('aName', 'name', $pass);
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The "enqueue.clients" parameter must be set.');
+ $pass->process(new ContainerBuilder());
}
- public function testThrowIfNameEmptyOnConstruct()
+ public function testThrowsIfNoRouteCollectionServiceFoundForConfiguredTransport()
{
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The name could not be empty.');
- new BuildCommandSubscriberRoutesPass('');
- }
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo', 'bar']);
+ $container->setParameter('enqueue.default_client', 'baz');
- public function testShouldDoNothingIfRouteCollectionServiceIsNotRegistered()
- {
- $pass = new BuildCommandSubscriberRoutesPass('aName');
- $pass->process(new ContainerBuilder());
+ $pass = new BuildCommandSubscriberRoutesPass();
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Service "enqueue.client.foo.route_collection" not found');
+ $pass->process($container);
}
public function testThrowIfTaggedProcessorIsBuiltByFactory()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['aName']);
+ $container->setParameter('enqueue.default_client', 'foo');
$container->register('enqueue.client.aName.route_collection', RouteCollection::class)
->addArgument([])
;
@@ -60,7 +64,7 @@ public function testThrowIfTaggedProcessorIsBuiltByFactory()
->addTag('enqueue.command_subscriber')
;
- $pass = new BuildCommandSubscriberRoutesPass('aName');
+ $pass = new BuildCommandSubscriberRoutesPass();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The command subscriber tag could not be applied to a service created by factory.');
@@ -73,6 +77,8 @@ public function testShouldRegisterProcessorWithMatchedName()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
$container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', get_class($this->createCommandSubscriberProcessor()))
->addTag('enqueue.command_subscriber', ['client' => 'foo'])
@@ -81,11 +87,11 @@ public function testShouldRegisterProcessorWithMatchedName()
->addTag('enqueue.command_subscriber', ['client' => 'bar'])
;
- $pass = new BuildCommandSubscriberRoutesPass('foo');
+ $pass = new BuildCommandSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
}
@@ -95,7 +101,9 @@ public function testShouldRegisterProcessorWithoutNameToDefaultClient()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', get_class($this->createCommandSubscriberProcessor()))
->addTag('enqueue.command_subscriber')
;
@@ -103,11 +111,11 @@ public function testShouldRegisterProcessorWithoutNameToDefaultClient()
->addTag('enqueue.command_subscriber', ['client' => 'bar'])
;
- $pass = new BuildCommandSubscriberRoutesPass('default');
+ $pass = new BuildCommandSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
}
@@ -117,7 +125,9 @@ public function testShouldRegisterProcessorIfClientNameEqualsAll()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', get_class($this->createCommandSubscriberProcessor()))
->addTag('enqueue.command_subscriber', ['client' => 'all'])
;
@@ -125,11 +135,11 @@ public function testShouldRegisterProcessorIfClientNameEqualsAll()
->addTag('enqueue.command_subscriber', ['client' => 'bar'])
;
- $pass = new BuildCommandSubscriberRoutesPass('default');
+ $pass = new BuildCommandSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
}
@@ -141,15 +151,17 @@ public function testShouldRegisterProcessorIfCommandsIsString()
$processor = $this->createCommandSubscriberProcessor('fooCommand');
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.command_subscriber')
;
- $pass = new BuildCommandSubscriberRoutesPass('default');
+ $pass = new BuildCommandSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
$this->assertEquals(
@@ -173,12 +185,14 @@ public function testThrowIfCommandSubscriberReturnsNothing()
$processor = $this->createCommandSubscriberProcessor(null);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.command_subscriber')
;
- $pass = new BuildCommandSubscriberRoutesPass('default');
+ $pass = new BuildCommandSubscriberRoutesPass();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Command subscriber must return something.');
@@ -193,15 +207,17 @@ public function testShouldRegisterProcessorIfCommandsAreStrings()
$processor = $this->createCommandSubscriberProcessor(['fooCommand', 'barCommand']);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.command_subscriber')
;
- $pass = new BuildCommandSubscriberRoutesPass('default');
+ $pass = new BuildCommandSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(2, $routeCollection->getArgument(0));
$this->assertEquals(
@@ -235,15 +251,17 @@ public function testShouldRegisterProcessorIfParamSingleCommandArray()
]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.command_subscriber')
;
- $pass = new BuildCommandSubscriberRoutesPass('default');
+ $pass = new BuildCommandSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
@@ -272,15 +290,17 @@ public function testShouldRegisterProcessorIfCommandsAreParamArrays()
]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.command_subscriber')
;
- $pass = new BuildCommandSubscriberRoutesPass('default');
+ $pass = new BuildCommandSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(2, $routeCollection->getArgument(0));
$this->assertEquals(
@@ -312,12 +332,14 @@ public function testThrowIfCommandSubscriberParamsInvalid()
$processor = $this->createCommandSubscriberProcessor(['fooBar', true]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.command_subscriber')
;
- $pass = new BuildCommandSubscriberRoutesPass('default');
+ $pass = new BuildCommandSubscriberRoutesPass();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Command subscriber configuration is invalid');
@@ -335,15 +357,17 @@ public function testShouldMergeExtractedRoutesWithAlreadySetInCollection()
$processor = $this->createCommandSubscriberProcessor(['fooCommand']);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.command_subscriber')
;
- $pass = new BuildCommandSubscriberRoutesPass('default');
+ $pass = new BuildCommandSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(3, $routeCollection->getArgument(0));
$this->assertEquals(
@@ -369,13 +393,57 @@ public function testShouldMergeExtractedRoutesWithAlreadySetInCollection()
);
}
+ public function testShouldRegister08CommandProcessor()
+ {
+ $routeCollection = new Definition(RouteCollection::class);
+ $routeCollection->addArgument([]);
+
+ $processor = $this->createCommandSubscriberProcessor([
+ 'processorName' => 'fooCommand',
+ 'queueName' => 'a_client_queue_name',
+ 'queueNameHardcoded' => true,
+ 'exclusive' => true,
+ 'anOption' => 'aFooVal',
+ ]);
+
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['default']);
+ $container->setParameter('enqueue.default_client', 'default');
+ $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
+ ->addTag('enqueue.command_subscriber')
+ ;
+
+ $pass = new BuildCommandSubscriberRoutesPass();
+ $pass->process($container);
+
+ self::assertIsArray($routeCollection->getArgument(0));
+ $this->assertCount(1, $routeCollection->getArgument(0));
+
+ $this->assertEquals(
+ [
+ [
+ 'source' => 'fooCommand',
+ 'source_type' => 'enqueue.client.command_route',
+ 'processor' => 'aFooProcessor',
+ 'processor_service_id' => 'aFooProcessor',
+ 'anOption' => 'aFooVal',
+ 'queue' => 'a_client_queue_name',
+ 'prefix_queue' => false,
+ ],
+ ],
+ $routeCollection->getArgument(0)
+ );
+ }
+
private function createCommandSubscriberProcessor($commandSubscriberReturns = ['aCommand'])
{
- $processor = new class() implements Processor, CommandSubscriberInterface {
+ $processor = new class implements Processor, CommandSubscriberInterface {
public static $return;
public function process(InteropMessage $message, Context $context)
{
+ return self::ACK;
}
public static function getSubscribedCommand()
diff --git a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildConsumptionExtensionsPassTest.php b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildConsumptionExtensionsPassTest.php
index 68ad2ab3e..c2975051b 100644
--- a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildConsumptionExtensionsPassTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildConsumptionExtensionsPassTest.php
@@ -25,28 +25,25 @@ public function testShouldBeFinal()
$this->assertClassFinal(BuildConsumptionExtensionsPass::class);
}
- public function testCouldBeConstructedWithName()
+ public function testThrowIfEnqueueClientsParameterNotSet()
{
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $pass = new BuildConsumptionExtensionsPass();
- $this->assertAttributeSame('aName', 'name', $pass);
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The "enqueue.clients" parameter must be set.');
+ $pass->process(new ContainerBuilder());
}
- public function testThrowIfNameEmptyOnConstruct()
- {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The name could not be empty.');
- new BuildConsumptionExtensionsPass('');
- }
-
- public function testShouldDoNothingIfExtensionsServiceIsNotRegistered()
+ public function testThrowsIfNoConsumptionExtensionsServiceFoundForConfiguredTransport()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo', 'bar']);
+ $container->setParameter('enqueue.default_client', 'baz');
- //guard
- $this->assertFalse($container->hasDefinition('enqueue.client.aName.consumption_extensions'));
+ $pass = new BuildConsumptionExtensionsPass();
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Service "enqueue.client.foo.consumption_extensions" not found');
$pass->process($container);
}
@@ -56,19 +53,21 @@ public function testShouldRegisterClientExtension()
$extensions->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.aName.consumption_extensions', $extensions);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.consumption_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
- ->addTag('enqueue.consumption_extension', ['client' => 'aName'])
+ ->addTag('enqueue.consumption_extension', ['client' => 'foo'])
;
$container->register('aBarExtension', ExtensionInterface::class)
- ->addTag('enqueue.consumption_extension', ['client' => 'aName'])
+ ->addTag('enqueue.consumption_extension', ['client' => 'foo'])
;
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
new Reference('aBarExtension'),
@@ -81,19 +80,21 @@ public function testShouldIgnoreOtherClientExtensions()
$extensions->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.aName.consumption_extensions', $extensions);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.consumption_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
- ->addTag('enqueue.consumption_extension', ['client' => 'aName'])
+ ->addTag('enqueue.consumption_extension', ['client' => 'foo'])
;
$container->register('aBarExtension', ExtensionInterface::class)
->addTag('enqueue.consumption_extension', ['client' => 'anotherName'])
;
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
], $extensions->getArgument(0));
@@ -105,7 +106,9 @@ public function testShouldAddExtensionIfClientAll()
$extensions->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.aName.consumption_extensions', $extensions);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.consumption_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
->addTag('enqueue.consumption_extension', ['client' => 'all'])
@@ -114,10 +117,10 @@ public function testShouldAddExtensionIfClientAll()
->addTag('enqueue.consumption_extension', ['client' => 'anotherName'])
;
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
], $extensions->getArgument(0));
@@ -129,7 +132,9 @@ public function testShouldTreatTagsWithoutClientAsDefaultClient()
$extensions->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.consumption_extensions', $extensions);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.consumption_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
->addTag('enqueue.consumption_extension')
@@ -138,10 +143,10 @@ public function testShouldTreatTagsWithoutClientAsDefaultClient()
->addTag('enqueue.consumption_extension')
;
- $pass = new BuildConsumptionExtensionsPass('default');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
new Reference('aBarExtension'),
@@ -151,10 +156,12 @@ public function testShouldTreatTagsWithoutClientAsDefaultClient()
public function testShouldOrderExtensionsByPriority()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
$extensions = new Definition();
$extensions->addArgument([]);
- $container->setDefinition('enqueue.client.default.consumption_extensions', $extensions);
+ $container->setDefinition('enqueue.client.foo.consumption_extensions', $extensions);
$extension = new Definition();
$extension->addTag('enqueue.consumption_extension', ['priority' => 6]);
@@ -168,7 +175,7 @@ public function testShouldOrderExtensionsByPriority()
$extension->addTag('enqueue.consumption_extension', ['priority' => 2]);
$container->setDefinition('baz_extension', $extension);
- $pass = new BuildConsumptionExtensionsPass('default');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
$orderedExtensions = $extensions->getArgument(0);
@@ -182,10 +189,12 @@ public function testShouldOrderExtensionsByPriority()
public function testShouldAssumePriorityZeroIfPriorityIsNotSet()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
$extensions = new Definition();
$extensions->addArgument([]);
- $container->setDefinition('enqueue.client.default.consumption_extensions', $extensions);
+ $container->setDefinition('enqueue.client.foo.consumption_extensions', $extensions);
$extension = new Definition();
$extension->addTag('enqueue.consumption_extension');
@@ -199,7 +208,7 @@ public function testShouldAssumePriorityZeroIfPriorityIsNotSet()
$extension->addTag('enqueue.consumption_extension', ['priority' => -1]);
$container->setDefinition('baz_extension', $extension);
- $pass = new BuildConsumptionExtensionsPass('default');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
$orderedExtensions = $extensions->getArgument(0);
@@ -219,7 +228,9 @@ public function testShouldMergeWithAddedPreviously()
]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.aName.consumption_extensions', $extensions);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.consumption_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
->addTag('enqueue.consumption_extension')
@@ -228,13 +239,45 @@ public function testShouldMergeWithAddedPreviously()
->addTag('enqueue.consumption_extension')
;
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $pass = new BuildConsumptionExtensionsPass();
+ $pass->process($container);
+
+ self::assertIsArray($extensions->getArgument(0));
+ $this->assertCount(4, $extensions->getArgument(0));
+ }
+
+ public function testShouldRegisterProcessorWithMatchedNameToCorrespondingExtensions()
+ {
+ $fooExtensions = new Definition();
+ $fooExtensions->addArgument([]);
+
+ $barExtensions = new Definition();
+ $barExtensions->addArgument([]);
+
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo', 'bar']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.consumption_extensions', $fooExtensions);
+ $container->setDefinition('enqueue.client.bar.consumption_extensions', $barExtensions);
+
+ $container->register('aFooExtension', ExtensionInterface::class)
+ ->addTag('enqueue.consumption_extension', ['client' => 'foo'])
+ ;
+ $container->register('aBarExtension', ExtensionInterface::class)
+ ->addTag('enqueue.consumption_extension', ['client' => 'bar'])
+ ;
+
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($fooExtensions->getArgument(0));
$this->assertEquals([
- 'aBarExtension' => 'aBarServiceIdAddedPreviously',
- 'aOloloExtension' => 'aOloloServiceIdAddedPreviously',
- ], $extensions->getArgument(0));
+ new Reference('aFooExtension'),
+ ], $fooExtensions->getArgument(0));
+
+ self::assertIsArray($barExtensions->getArgument(0));
+ $this->assertEquals([
+ new Reference('aBarExtension'),
+ ], $barExtensions->getArgument(0));
}
}
diff --git a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRegistryPassTest.php b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRegistryPassTest.php
index 59796521f..5c9ac4840 100644
--- a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRegistryPassTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRegistryPassTest.php
@@ -6,6 +6,7 @@
use Enqueue\Symfony\Client\DependencyInjection\BuildProcessorRegistryPass;
use Enqueue\Test\ClassExtensionTrait;
use PHPUnit\Framework\TestCase;
+use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
@@ -25,70 +26,65 @@ public function testShouldBeFinal()
$this->assertClassFinal(BuildProcessorRegistryPass::class);
}
- public function testCouldBeConstructedWithName()
+ public function testThrowIfEnqueueClientsParameterNotSet()
{
- $pass = new BuildProcessorRegistryPass('aName');
+ $pass = new BuildProcessorRegistryPass();
- $this->assertAttributeSame('aName', 'name', $pass);
- }
-
- public function testThrowIfNameEmptyOnConstruct()
- {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The name could not be empty.');
- new BuildProcessorRegistryPass('');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The "enqueue.clients" parameter must be set.');
+ $pass->process(new ContainerBuilder());
}
- public function testShouldDoNothingIfRouteCollectionServiceIsNotRegistered()
+ public function testThrowsIfNoProcessorRegistryServiceFoundForConfiguredTransport()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo', 'bar']);
- //guard
- $this->assertFalse($container->hasDefinition('enqueue.client.aName.route_collection'));
+ $pass = new BuildProcessorRegistryPass();
- $pass = new BuildProcessorRegistryPass('aName');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Service "enqueue.client.foo.processor_registry" not found');
$pass->process($container);
}
- public function testShouldDoNothingIfProcessorRegistryCollectionServiceIsNotRegistered()
+ public function testThrowsIfNoRouteCollectionServiceFoundForConfiguredTransport()
{
$container = new ContainerBuilder();
- $container->register('enqueue.client.aName.route_collection');
+ $container->setParameter('enqueue.clients', ['foo', 'bar']);
+ $container->register('enqueue.client.foo.processor_registry');
- //guard
- $this->assertFalse($container->hasDefinition('enqueue.client.aName.processor_registry'));
+ $pass = new BuildProcessorRegistryPass();
- $pass = new BuildProcessorRegistryPass('aName');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Service "enqueue.client.foo.route_collection" not found');
$pass->process($container);
}
- public function testShouldDoNothingIfRouterProcessorServiceIsNotRegistered()
+ public function testThrowsIfNoRouteProcessorServiceFoundForConfiguredTransport()
{
$container = new ContainerBuilder();
- $container->register('enqueue.client.aName.route_collection');
- $container->register('enqueue.client.aName.processor_registry')
- ->addArgument([])
- ;
+ $container->setParameter('enqueue.clients', ['foo', 'bar']);
+ $container->register('enqueue.client.foo.processor_registry');
+ $container->register('enqueue.client.foo.route_collection');
- //guard
- $this->assertFalse($container->hasDefinition('enqueue.client.aName.router_processor'));
+ $pass = new BuildProcessorRegistryPass();
- $pass = new BuildProcessorRegistryPass('aName');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Service "enqueue.client.foo.router_processor" not found');
$pass->process($container);
-
- $this->assertSame([], $container->getDefinition('enqueue.client.aName.processor_registry')->getArgument(0));
}
public function testThrowIfProcessorServiceIdOptionNotSet()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['aName']);
$container->register('enqueue.client.aName.route_collection')->addArgument([
(new Route('aCommand', Route::COMMAND, 'aProcessor'))->toArray(),
]);
$container->register('enqueue.client.aName.processor_registry')->addArgument([]);
$container->register('enqueue.client.aName.router_processor');
- $pass = new BuildProcessorRegistryPass('aName');
+ $pass = new BuildProcessorRegistryPass();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The route option "processor_service_id" is required');
@@ -101,6 +97,7 @@ public function testShouldPassLocatorAsFirstArgument()
$registry->addArgument([]);
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['aName']);
$container->register('enqueue.client.aName.route_collection')->addArgument([
(new Route(
'aCommand',
@@ -118,10 +115,37 @@ public function testShouldPassLocatorAsFirstArgument()
$container->setDefinition('enqueue.client.aName.processor_registry', $registry);
$container->register('enqueue.client.aName.router_processor');
- $pass = new BuildProcessorRegistryPass('aName');
+ $pass = new BuildProcessorRegistryPass();
$pass->process($container);
- $this->assertInstanceOf(Reference::class, $registry->getArgument(0));
- $this->assertRegExp('/service_locator\..*?\.enqueue\.client\.aName\.processor_registry/', (string) $registry->getArgument(0));
+ $this->assertLocatorServices($container, $registry->getArgument(0), [
+ '%enqueue.client.aName.router_processor%' => 'enqueue.client.aName.router_processor',
+ 'aBarProcessor' => 'aBarServiceId',
+ 'aFooProcessor' => 'aFooServiceId',
+ ]);
+ }
+
+ private function assertLocatorServices(ContainerBuilder $container, $locatorId, array $locatorServices)
+ {
+ $this->assertInstanceOf(Reference::class, $locatorId);
+ $locatorId = (string) $locatorId;
+
+ $this->assertTrue($container->hasDefinition($locatorId));
+ $this->assertMatchesRegularExpression('/\.?service_locator\..*?\.enqueue\./', $locatorId);
+
+ $match = [];
+ if (false == preg_match('/(\.?service_locator\..*?)\.enqueue\./', $locatorId, $match)) {
+ $this->fail('preg_match should not failed');
+ }
+
+ $this->assertTrue($container->hasDefinition($match[1]));
+ $locator = $container->getDefinition($match[1]);
+
+ $this->assertContainsOnly(ServiceClosureArgument::class, $locator->getArgument(0));
+ $actualServices = array_map(function (ServiceClosureArgument $value) {
+ return (string) $value->getValues()[0];
+ }, $locator->getArgument(0));
+
+ $this->assertEquals($locatorServices, $actualServices);
}
}
diff --git a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRoutesPassTest.php b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRoutesPassTest.php
index b0d7af5eb..0351c45f5 100644
--- a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRoutesPassTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRoutesPassTest.php
@@ -25,24 +25,26 @@ public function testShouldBeFinal()
$this->assertClassFinal(BuildProcessorRoutesPass::class);
}
- public function testCouldBeConstructedWithName()
+ public function testThrowIfEnqueueClientsParameterNotSet()
{
- $pass = new BuildProcessorRoutesPass('aName');
+ $pass = new BuildProcessorRoutesPass();
- $this->assertAttributeSame('aName', 'name', $pass);
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The "enqueue.clients" parameter must be set.');
+ $pass->process(new ContainerBuilder());
}
- public function testThrowIfNameEmptyOnConstruct()
+ public function testThrowsIfNoRouteCollectionServiceFoundForConfiguredTransport()
{
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The name could not be empty.');
- new BuildProcessorRoutesPass('');
- }
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo', 'bar']);
+ $container->setParameter('enqueue.default_client', 'baz');
- public function testShouldDoNothingIfRouteCollectionServiceIsNotRegistered()
- {
- $pass = new BuildProcessorRoutesPass('aName');
- $pass->process(new ContainerBuilder());
+ $pass = new BuildProcessorRoutesPass();
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Service "enqueue.client.foo.route_collection" not found');
+ $pass->process($container);
}
public function testThrowIfBothTopicAndCommandAttributesAreSet()
@@ -51,12 +53,14 @@ public function testThrowIfBothTopicAndCommandAttributesAreSet()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.processor', ['topic' => 'foo', 'command' => 'bar'])
;
- $pass = new BuildProcessorRoutesPass('default');
+ $pass = new BuildProcessorRoutesPass();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Either "topic" or "command" tag attribute must be set on service "aFooProcessor". Both are set.');
@@ -69,12 +73,14 @@ public function testThrowIfNeitherTopicNorCommandAttributesAreSet()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.processor', [])
;
- $pass = new BuildProcessorRoutesPass('default');
+ $pass = new BuildProcessorRoutesPass();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Either "topic" or "command" tag attribute must be set on service "aFooProcessor". None is set.');
@@ -87,6 +93,8 @@ public function testShouldRegisterProcessorWithMatchedName()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'bar');
$container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.processor', ['client' => 'foo', 'topic' => 'foo'])
@@ -95,11 +103,11 @@ public function testShouldRegisterProcessorWithMatchedName()
->addTag('enqueue.processor', ['client' => 'bar', 'command' => 'foo'])
;
- $pass = new BuildProcessorRoutesPass('foo');
+ $pass = new BuildProcessorRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
}
@@ -109,7 +117,9 @@ public function testShouldRegisterProcessorWithoutNameToDefaultClient()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.processor', ['topic' => 'foo'])
;
@@ -117,11 +127,11 @@ public function testShouldRegisterProcessorWithoutNameToDefaultClient()
->addTag('enqueue.processor', ['client' => 'bar', 'command' => 'foo'])
;
- $pass = new BuildProcessorRoutesPass('default');
+ $pass = new BuildProcessorRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
}
@@ -131,7 +141,9 @@ public function testShouldRegisterProcessorIfClientNameEqualsAll()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.processor', ['client' => 'all', 'topic' => 'foo'])
;
@@ -139,11 +151,11 @@ public function testShouldRegisterProcessorIfClientNameEqualsAll()
->addTag('enqueue.processor', ['client' => 'bar', 'command' => 'foo'])
;
- $pass = new BuildProcessorRoutesPass('default');
+ $pass = new BuildProcessorRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
}
@@ -153,15 +165,17 @@ public function testShouldRegisterAsTopicProcessor()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.processor', ['topic' => 'aTopic'])
;
- $pass = new BuildProcessorRoutesPass('default');
+ $pass = new BuildProcessorRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
$this->assertEquals(
@@ -183,15 +197,17 @@ public function testShouldRegisterAsCommandProcessor()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.processor', ['command' => 'aCommand'])
;
- $pass = new BuildProcessorRoutesPass('default');
+ $pass = new BuildProcessorRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
$this->assertEquals(
@@ -213,15 +229,17 @@ public function testShouldRegisterWithCustomProcessorName()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.processor', ['command' => 'aCommand', 'processor' => 'customProcessorName'])
;
- $pass = new BuildProcessorRoutesPass('default');
+ $pass = new BuildProcessorRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
$this->assertEquals(
@@ -246,15 +264,17 @@ public function testShouldMergeExtractedRoutesWithAlreadySetInCollection()
]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.processor', ['command' => 'fooCommand'])
;
- $pass = new BuildProcessorRoutesPass('default');
+ $pass = new BuildProcessorRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(3, $routeCollection->getArgument(0));
$this->assertEquals(
diff --git a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildTopicSubscriberRoutesPassTest.php b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildTopicSubscriberRoutesPassTest.php
index 895cfb11d..a954d9a41 100644
--- a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildTopicSubscriberRoutesPassTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildTopicSubscriberRoutesPassTest.php
@@ -29,30 +29,34 @@ public function testShouldBeFinal()
$this->assertClassFinal(BuildTopicSubscriberRoutesPass::class);
}
- public function testCouldBeConstructedWithName()
+ public function testThrowIfEnqueueClientsParameterNotSet()
{
- $pass = new BuildTopicSubscriberRoutesPass('aName');
+ $pass = new BuildTopicSubscriberRoutesPass();
- $this->assertAttributeSame('aName', 'name', $pass);
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The "enqueue.clients" parameter must be set.');
+ $pass->process(new ContainerBuilder());
}
- public function testThrowIfNameEmptyOnConstruct()
+ public function testThrowsIfNoRouteCollectionServiceFoundForConfiguredTransport()
{
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The name could not be empty.');
- new BuildTopicSubscriberRoutesPass('');
- }
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo', 'bar']);
+ $container->setParameter('enqueue.default_client', 'baz');
- public function testShouldDoNothingIfRouteCollectionServiceIsNotRegistered()
- {
- $pass = new BuildTopicSubscriberRoutesPass('aName');
- $pass->process(new ContainerBuilder());
+ $pass = new BuildTopicSubscriberRoutesPass();
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Service "enqueue.client.foo.route_collection" not found');
+ $pass->process($container);
}
public function testThrowIfTaggedProcessorIsBuiltByFactory()
{
$container = new ContainerBuilder();
- $container->register('enqueue.client.aName.route_collection', RouteCollection::class)
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->register('enqueue.client.foo.route_collection', RouteCollection::class)
->addArgument([])
;
$container->register('aProcessor', Processor::class)
@@ -60,7 +64,7 @@ public function testThrowIfTaggedProcessorIsBuiltByFactory()
->addTag('enqueue.topic_subscriber')
;
- $pass = new BuildTopicSubscriberRoutesPass('aName');
+ $pass = new BuildTopicSubscriberRoutesPass();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The topic subscriber tag could not be applied to a service created by factory.');
@@ -73,6 +77,8 @@ public function testShouldRegisterProcessorWithMatchedName()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'bar');
$container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', get_class($this->createTopicSubscriberProcessor()))
->addTag('enqueue.topic_subscriber', ['client' => 'foo'])
@@ -81,11 +87,11 @@ public function testShouldRegisterProcessorWithMatchedName()
->addTag('enqueue.topic_subscriber', ['client' => 'bar'])
;
- $pass = new BuildTopicSubscriberRoutesPass('foo');
+ $pass = new BuildTopicSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
}
@@ -95,7 +101,9 @@ public function testShouldRegisterProcessorWithoutNameToDefaultClient()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', get_class($this->createTopicSubscriberProcessor()))
->addTag('enqueue.topic_subscriber')
;
@@ -103,11 +111,11 @@ public function testShouldRegisterProcessorWithoutNameToDefaultClient()
->addTag('enqueue.topic_subscriber', ['client' => 'bar'])
;
- $pass = new BuildTopicSubscriberRoutesPass('default');
+ $pass = new BuildTopicSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
}
@@ -117,7 +125,9 @@ public function testShouldRegisterProcessorIfClientNameEqualsAll()
$routeCollection->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
$container->register('aFooProcessor', get_class($this->createTopicSubscriberProcessor()))
->addTag('enqueue.topic_subscriber', ['client' => 'all'])
;
@@ -125,11 +135,11 @@ public function testShouldRegisterProcessorIfClientNameEqualsAll()
->addTag('enqueue.topic_subscriber', ['client' => 'bar'])
;
- $pass = new BuildTopicSubscriberRoutesPass('default');
+ $pass = new BuildTopicSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
}
@@ -141,15 +151,17 @@ public function testShouldRegisterProcessorIfTopicsIsString()
$processor = $this->createTopicSubscriberProcessor('fooTopic');
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.topic_subscriber')
;
- $pass = new BuildTopicSubscriberRoutesPass('default');
+ $pass = new BuildTopicSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(1, $routeCollection->getArgument(0));
$this->assertEquals(
@@ -173,12 +185,14 @@ public function testThrowIfTopicSubscriberReturnsNothing()
$processor = $this->createTopicSubscriberProcessor(null);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.topic_subscriber')
;
- $pass = new BuildTopicSubscriberRoutesPass('default');
+ $pass = new BuildTopicSubscriberRoutesPass();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Topic subscriber must return something.');
@@ -193,15 +207,17 @@ public function testShouldRegisterProcessorIfTopicsAreStrings()
$processor = $this->createTopicSubscriberProcessor(['fooTopic', 'barTopic']);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.topic_subscriber')
;
- $pass = new BuildTopicSubscriberRoutesPass('default');
+ $pass = new BuildTopicSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(2, $routeCollection->getArgument(0));
$this->assertEquals(
@@ -234,15 +250,17 @@ public function testShouldRegisterProcessorIfTopicsAreParamArrays()
]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.topic_subscriber')
;
- $pass = new BuildTopicSubscriberRoutesPass('default');
+ $pass = new BuildTopicSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(2, $routeCollection->getArgument(0));
$this->assertEquals(
@@ -274,12 +292,14 @@ public function testThrowIfTopicSubscriberParamsInvalid()
$processor = $this->createTopicSubscriberProcessor(['fooBar', true]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.topic_subscriber')
;
- $pass = new BuildTopicSubscriberRoutesPass('default');
+ $pass = new BuildTopicSubscriberRoutesPass();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Topic subscriber configuration is invalid');
@@ -297,15 +317,17 @@ public function testShouldMergeExtractedRoutesWithAlreadySetInCollection()
$processor = $this->createTopicSubscriberProcessor(['fooTopic']);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
- $container->register('aFooProcessor', get_class($processor))
+ $container->setParameter('enqueue.clients', ['foo']);
+ $container->setParameter('enqueue.default_client', 'foo');
+ $container->setDefinition('enqueue.client.foo.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
->addTag('enqueue.topic_subscriber')
;
- $pass = new BuildTopicSubscriberRoutesPass('default');
+ $pass = new BuildTopicSubscriberRoutesPass();
$pass->process($container);
- $this->assertInternalType('array', $routeCollection->getArgument(0));
+ self::assertIsArray($routeCollection->getArgument(0));
$this->assertCount(3, $routeCollection->getArgument(0));
$this->assertEquals(
@@ -331,13 +353,61 @@ public function testShouldMergeExtractedRoutesWithAlreadySetInCollection()
);
}
+ public function testShouldRegister08TopicSubscriber()
+ {
+ $routeCollection = new Definition(RouteCollection::class);
+ $routeCollection->addArgument([]);
+
+ $processor = $this->createTopicSubscriberProcessor([
+ 'fooTopic' => ['processorName' => 'aCustomFooProcessorName', 'queueName' => 'fooQueue', 'queueNameHardcoded' => true, 'anOption' => 'aFooVal'],
+ 'barTopic' => ['processorName' => 'aCustomBarProcessorName', 'anOption' => 'aBarVal'],
+ ]);
+
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.clients', ['default']);
+ $container->setParameter('enqueue.default_client', 'default');
+ $container->setDefinition('enqueue.client.default.route_collection', $routeCollection);
+ $container->register('aFooProcessor', $processor::class)
+ ->addTag('enqueue.topic_subscriber')
+ ;
+
+ $pass = new BuildTopicSubscriberRoutesPass();
+ $pass->process($container);
+
+ self::assertIsArray($routeCollection->getArgument(0));
+ $this->assertCount(2, $routeCollection->getArgument(0));
+
+ $this->assertEquals(
+ [
+ [
+ 'source' => 'fooTopic',
+ 'source_type' => 'enqueue.client.topic_route',
+ 'processor' => 'aCustomFooProcessorName',
+ 'processor_service_id' => 'aFooProcessor',
+ 'anOption' => 'aFooVal',
+ 'queue' => 'fooQueue',
+ 'prefix_queue' => false,
+ ],
+ [
+ 'source' => 'barTopic',
+ 'source_type' => 'enqueue.client.topic_route',
+ 'processor' => 'aCustomBarProcessorName',
+ 'processor_service_id' => 'aFooProcessor',
+ 'anOption' => 'aBarVal',
+ ],
+ ],
+ $routeCollection->getArgument(0)
+ );
+ }
+
private function createTopicSubscriberProcessor($topicSubscriberReturns = ['aTopic'])
{
- $processor = new class() implements Processor, TopicSubscriberInterface {
+ $processor = new class implements Processor, TopicSubscriberInterface {
public static $return;
public function process(InteropMessage $message, Context $context)
{
+ return self::ACK;
}
public static function getSubscribedTopics()
diff --git a/pkg/enqueue/Tests/Symfony/DependencyInjection/ClientFactoryTest.php b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/ClientFactoryTest.php
similarity index 80%
rename from pkg/enqueue/Tests/Symfony/DependencyInjection/ClientFactoryTest.php
rename to pkg/enqueue/Tests/Symfony/Client/DependencyInjection/ClientFactoryTest.php
index bb4cfe9a4..9f37dff47 100644
--- a/pkg/enqueue/Tests/Symfony/DependencyInjection/ClientFactoryTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/ClientFactoryTest.php
@@ -1,8 +1,8 @@
assertClassFinal(ClientFactory::class);
}
- public function testShouldAllowGetNameSetInConstructor()
- {
- $transport = new ClientFactory('aName');
-
- $this->assertEquals('aName', $transport->getName());
- }
-
public function testThrowIfEmptyNameGivenOnConstruction()
{
$this->expectException(\InvalidArgumentException::class);
@@ -52,8 +45,8 @@ public function testShouldCreateDriverFromDsn()
$this->assertEquals(
[
new Reference('enqueue.transport.default.connection_factory'),
- 'foo://bar/baz',
- ['dsn' => 'foo://bar/baz', 'foo' => 'fooVal'],
+ new Reference('enqueue.client.default.config'),
+ new Reference('enqueue.client.default.route_collection'),
],
$container->getDefinition('enqueue.client.default.driver')->getArguments())
;
diff --git a/pkg/enqueue/Tests/Symfony/Client/FlushSpoolProducerListenerTest.php b/pkg/enqueue/Tests/Symfony/Client/FlushSpoolProducerListenerTest.php
index a1fe06e7a..539d332ee 100644
--- a/pkg/enqueue/Tests/Symfony/Client/FlushSpoolProducerListenerTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/FlushSpoolProducerListenerTest.php
@@ -23,7 +23,7 @@ public function testShouldSubscribeOnKernelTerminateEvent()
{
$events = FlushSpoolProducerListener::getSubscribedEvents();
- $this->assertInternalType('array', $events);
+ self::assertIsArray($events);
$this->assertArrayHasKey(KernelEvents::TERMINATE, $events);
$this->assertEquals('flushMessages', $events[KernelEvents::TERMINATE]);
@@ -33,17 +33,12 @@ public function testShouldSubscribeOnConsoleTerminateEvent()
{
$events = FlushSpoolProducerListener::getSubscribedEvents();
- $this->assertInternalType('array', $events);
+ self::assertIsArray($events);
$this->assertArrayHasKey(ConsoleEvents::TERMINATE, $events);
$this->assertEquals('flushMessages', $events[ConsoleEvents::TERMINATE]);
}
- public function testCouldBeConstructedWithSpoolProducerAsFirstArgument()
- {
- new FlushSpoolProducerListener($this->createSpoolProducerMock());
- }
-
public function testShouldFlushSpoolProducerOnFlushMessagesCall()
{
$producerMock = $this->createSpoolProducerMock();
@@ -58,7 +53,7 @@ public function testShouldFlushSpoolProducerOnFlushMessagesCall()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|SpoolProducer
+ * @return \PHPUnit\Framework\MockObject\MockObject|SpoolProducer
*/
private function createSpoolProducerMock()
{
diff --git a/pkg/enqueue/Tests/Symfony/Client/Mock/SetupBrokerExtensionCommand.php b/pkg/enqueue/Tests/Symfony/Client/Mock/SetupBrokerExtensionCommand.php
index aa0c8126a..a4978eaf6 100644
--- a/pkg/enqueue/Tests/Symfony/Client/Mock/SetupBrokerExtensionCommand.php
+++ b/pkg/enqueue/Tests/Symfony/Client/Mock/SetupBrokerExtensionCommand.php
@@ -22,19 +22,21 @@ public function getExtension()
return $this->extension;
}
- protected function configure()
+ protected function configure(): void
{
parent::configure();
$this->configureSetupBrokerExtension();
}
- protected function execute(InputInterface $input, OutputInterface $output)
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->extension = $this->getSetupBrokerExtension($input, new GenericDriver(
new NullContext(),
Config::create(),
new RouteCollection([])
));
+
+ return 0;
}
}
diff --git a/pkg/enqueue/Tests/Symfony/Client/ProduceCommandTest.php b/pkg/enqueue/Tests/Symfony/Client/ProduceCommandTest.php
index 321b4eebd..daa909175 100644
--- a/pkg/enqueue/Tests/Symfony/Client/ProduceCommandTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/ProduceCommandTest.php
@@ -2,12 +2,14 @@
namespace Enqueue\Tests\Symfony\Client;
+use Enqueue\Client\Message;
use Enqueue\Client\ProducerInterface;
use Enqueue\Container\Container;
use Enqueue\Symfony\Client\ProduceCommand;
use Enqueue\Test\ClassExtensionTrait;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;
@@ -25,32 +27,39 @@ public function testShouldNotBeFinal()
$this->assertClassNotFinal(ProduceCommand::class);
}
- public function testCouldBeConstructedWithContainerAsFirstArgument()
+ public function testShouldHaveAsCommandAttributeWithCommandName()
{
- new ProduceCommand($this->createMock(ContainerInterface::class));
- }
+ $commandClass = ProduceCommand::class;
- public function testShouldHaveCommandName()
- {
- $command = new ProduceCommand($this->createMock(ContainerInterface::class));
+ $reflectionClass = new \ReflectionClass($commandClass);
+
+ $attributes = $reflectionClass->getAttributes(AsCommand::class);
+
+ $this->assertNotEmpty($attributes, 'The command does not have the AsCommand attribute.');
+
+ // Get the first attribute instance (assuming there is only one AsCommand attribute)
+ $asCommandAttribute = $attributes[0];
- $this->assertEquals('enqueue:produce', $command->getName());
+ // Verify the 'name' parameter value
+ $attributeInstance = $asCommandAttribute->newInstance();
+ $this->assertEquals('enqueue:produce', $attributeInstance->name, 'The command name is not set correctly in the AsCommand attribute.');
}
public function testShouldHaveExpectedOptions()
{
- $command = new ProduceCommand($this->createMock(ContainerInterface::class));
+ $command = new ProduceCommand($this->createMock(ContainerInterface::class), 'default');
$options = $command->getDefinition()->getOptions();
- $this->assertCount(3, $options);
+ $this->assertCount(4, $options);
$this->assertArrayHasKey('client', $options);
$this->assertArrayHasKey('topic', $options);
$this->assertArrayHasKey('command', $options);
+ $this->assertArrayHasKey('header', $options);
}
public function testShouldHaveExpectedAttributes()
{
- $command = new ProduceCommand($this->createMock(ContainerInterface::class));
+ $command = new ProduceCommand($this->createMock(ContainerInterface::class), 'default');
$arguments = $command->getDefinition()->getArguments();
$this->assertCount(1, $arguments);
@@ -72,7 +81,7 @@ public function testThrowIfNeitherTopicNorCommandOptionsAreSet()
$command = new ProduceCommand(new Container([
'enqueue.client.default.producer' => $producerMock,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -97,7 +106,7 @@ public function testThrowIfBothTopicAndCommandOptionsAreSet()
$command = new ProduceCommand(new Container([
'enqueue.client.default.producer' => $producerMock,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -112,11 +121,14 @@ public function testThrowIfBothTopicAndCommandOptionsAreSet()
public function testShouldSendEventToDefaultTransport()
{
+ $header = 'Content-Type: text/plain';
+ $payload = 'theMessage';
+
$producerMock = $this->createProducerMock();
$producerMock
->expects($this->once())
->method('sendEvent')
- ->with('theTopic', 'theMessage')
+ ->with('theTopic', new Message($payload, [], [$header]))
;
$producerMock
->expects($this->never())
@@ -125,11 +137,12 @@ public function testShouldSendEventToDefaultTransport()
$command = new ProduceCommand(new Container([
'enqueue.client.default.producer' => $producerMock,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
- 'message' => 'theMessage',
+ 'message' => $payload,
+ '--header' => $header,
'--topic' => 'theTopic',
]);
}
@@ -149,7 +162,7 @@ public function testShouldSendCommandToDefaultTransport()
$command = new ProduceCommand(new Container([
'enqueue.client.default.producer' => $producerMock,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
@@ -160,6 +173,9 @@ public function testShouldSendCommandToDefaultTransport()
public function testShouldSendEventToFooTransport()
{
+ $header = 'Content-Type: text/plain';
+ $payload = 'theMessage';
+
$defaultProducerMock = $this->createProducerMock();
$defaultProducerMock
->expects($this->never())
@@ -174,7 +190,7 @@ public function testShouldSendEventToFooTransport()
$fooProducerMock
->expects($this->once())
->method('sendEvent')
- ->with('theTopic', 'theMessage')
+ ->with('theTopic', new Message($payload, [], [$header]))
;
$fooProducerMock
->expects($this->never())
@@ -184,11 +200,12 @@ public function testShouldSendEventToFooTransport()
$command = new ProduceCommand(new Container([
'enqueue.client.default.producer' => $defaultProducerMock,
'enqueue.client.foo.producer' => $fooProducerMock,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
- 'message' => 'theMessage',
+ 'message' => $payload,
+ '--header' => $header,
'--topic' => 'theTopic',
'--client' => 'foo',
]);
@@ -220,7 +237,7 @@ public function testShouldSendCommandToFooTransport()
$command = new ProduceCommand(new Container([
'enqueue.client.default.producer' => $defaultProducerMock,
'enqueue.client.foo.producer' => $fooProducerMock,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
@@ -244,7 +261,7 @@ public function testThrowIfClientNotFound()
$command = new ProduceCommand(new Container([
'enqueue.client.default.producer' => $defaultProducerMock,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -258,7 +275,7 @@ public function testThrowIfClientNotFound()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ProducerInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|ProducerInterface
*/
private function createProducerMock()
{
diff --git a/pkg/enqueue/Tests/Symfony/Client/RoutesCommandTest.php b/pkg/enqueue/Tests/Symfony/Client/RoutesCommandTest.php
index daab37e1c..89bd7f745 100644
--- a/pkg/enqueue/Tests/Symfony/Client/RoutesCommandTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/RoutesCommandTest.php
@@ -11,6 +11,7 @@
use Enqueue\Test\ClassExtensionTrait;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;
@@ -28,28 +29,34 @@ public function testShouldNotBeFinal()
$this->assertClassNotFinal(RoutesCommand::class);
}
- public function testCouldBeConstructedWithConfigAndRouteCollectionAsArguments()
+ public function testShouldHaveAsCommandAttributeWithCommandName()
{
- new RoutesCommand($this->createMock(ContainerInterface::class));
- }
+ $commandClass = RoutesCommand::class;
- public function testShouldHaveCommandName()
- {
- $command = new RoutesCommand($this->createMock(ContainerInterface::class));
+ $reflectionClass = new \ReflectionClass($commandClass);
+
+ $attributes = $reflectionClass->getAttributes(AsCommand::class);
+
+ $this->assertNotEmpty($attributes, 'The command does not have the AsCommand attribute.');
+
+ // Get the first attribute instance (assuming there is only one AsCommand attribute)
+ $asCommandAttribute = $attributes[0];
- $this->assertEquals('enqueue:routes', $command->getName());
+ // Verify the 'name' parameter value
+ $attributeInstance = $asCommandAttribute->newInstance();
+ $this->assertEquals('enqueue:routes', $attributeInstance->name, 'The command name is not set correctly in the AsCommand attribute.');
}
public function testShouldHaveCommandAliases()
{
- $command = new RoutesCommand($this->createMock(ContainerInterface::class));
+ $command = new RoutesCommand($this->createMock(ContainerInterface::class), 'default');
$this->assertEquals(['debug:enqueue:routes'], $command->getAliases());
}
public function testShouldHaveExpectedOptions()
{
- $command = new RoutesCommand($this->createMock(ContainerInterface::class));
+ $command = new RoutesCommand($this->createMock(ContainerInterface::class), 'default');
$options = $command->getDefinition()->getOptions();
$this->assertCount(2, $options);
@@ -60,7 +67,7 @@ public function testShouldHaveExpectedOptions()
public function testShouldHaveExpectedAttributes()
{
- $command = new RoutesCommand($this->createMock(ContainerInterface::class));
+ $command = new RoutesCommand($this->createMock(ContainerInterface::class), 'default');
$arguments = $command->getDefinition()->getArguments();
$this->assertCount(0, $arguments);
@@ -72,7 +79,7 @@ public function testShouldOutputEmptyRouteCollection()
$command = new RoutesCommand(new Container([
'enqueue.client.default.driver' => $this->createDriverStub(Config::create(), $routeCollection),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -109,14 +116,14 @@ public function testShouldUseFooDriver()
$command = new RoutesCommand(new Container([
'enqueue.client.default.driver' => $defaultDriverMock,
'enqueue.client.foo.driver' => $fooDriverMock,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
'--client' => 'foo',
]);
- $this->assertContains('Found 1 routes', $tester->getDisplay());
+ $this->assertStringContainsString('Found 1 routes', $tester->getDisplay());
}
public function testThrowIfClientNotFound()
@@ -134,7 +141,7 @@ public function testThrowIfClientNotFound()
$command = new RoutesCommand(new Container([
'enqueue.client.default.driver' => $defaultDriverMock,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -154,7 +161,7 @@ public function testShouldOutputTopicRouteInfo()
$command = new RoutesCommand(new Container([
'enqueue.client.default.driver' => $this->createDriverStub(Config::create(), $routeCollection),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -184,7 +191,7 @@ public function testShouldOutputCommandRouteInfo()
$command = new RoutesCommand(new Container([
'enqueue.client.default.driver' => $this->createDriverStub(Config::create(), $routeCollection),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -214,7 +221,7 @@ public function testShouldCorrectlyOutputPrefixedCustomQueue()
$command = new RoutesCommand(new Container([
'enqueue.client.default.driver' => $this->createDriverStub(Config::create(), $routeCollection),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -245,7 +252,7 @@ public function testShouldCorrectlyOutputNotPrefixedCustomQueue()
$command = new RoutesCommand(new Container([
'enqueue.client.default.driver' => $this->createDriverStub(Config::create(), $routeCollection),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -275,7 +282,7 @@ public function testShouldCorrectlyOutputExternalRoute()
$command = new RoutesCommand(new Container([
'enqueue.client.default.driver' => $this->createDriverStub(Config::create(), $routeCollection),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -305,7 +312,7 @@ public function testShouldOutputRouteOptions()
$command = new RoutesCommand(new Container([
'enqueue.client.default.driver' => $this->createDriverStub(Config::create(), $routeCollection),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -331,7 +338,7 @@ public function testShouldOutputRouteOptions()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject|DriverInterface
*/
private function createDriverStub(Config $config, RouteCollection $routeCollection): DriverInterface
{
diff --git a/pkg/enqueue/Tests/Symfony/Client/SetupBrokerCommandTest.php b/pkg/enqueue/Tests/Symfony/Client/SetupBrokerCommandTest.php
index b81daf2b3..c81c4e1b6 100644
--- a/pkg/enqueue/Tests/Symfony/Client/SetupBrokerCommandTest.php
+++ b/pkg/enqueue/Tests/Symfony/Client/SetupBrokerCommandTest.php
@@ -8,6 +8,7 @@
use Enqueue\Test\ClassExtensionTrait;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;
@@ -25,28 +26,34 @@ public function testShouldNotBeFinal()
$this->assertClassNotFinal(SetupBrokerCommand::class);
}
- public function testCouldBeConstructedWithContainerAsFirstArgument()
+ public function testShouldHaveAsCommandAttributeWithCommandName()
{
- new SetupBrokerCommand($this->createMock(ContainerInterface::class));
- }
+ $commandClass = SetupBrokerCommand::class;
- public function testShouldHaveCommandName()
- {
- $command = new SetupBrokerCommand($this->createMock(ContainerInterface::class));
+ $reflectionClass = new \ReflectionClass($commandClass);
+
+ $attributes = $reflectionClass->getAttributes(AsCommand::class);
+
+ $this->assertNotEmpty($attributes, 'The command does not have the AsCommand attribute.');
+
+ // Get the first attribute instance (assuming there is only one AsCommand attribute)
+ $asCommandAttribute = $attributes[0];
- $this->assertEquals('enqueue:setup-broker', $command->getName());
+ // Verify the 'name' parameter value
+ $attributeInstance = $asCommandAttribute->newInstance();
+ $this->assertEquals('enqueue:setup-broker', $attributeInstance->name, 'The command name is not set correctly in the AsCommand attribute.');
}
public function testShouldHaveCommandAliases()
{
- $command = new SetupBrokerCommand($this->createMock(ContainerInterface::class));
+ $command = new SetupBrokerCommand($this->createMock(ContainerInterface::class), 'default');
$this->assertEquals(['enq:sb'], $command->getAliases());
}
public function testShouldHaveExpectedOptions()
{
- $command = new SetupBrokerCommand($this->createMock(ContainerInterface::class));
+ $command = new SetupBrokerCommand($this->createMock(ContainerInterface::class), 'default');
$options = $command->getDefinition()->getOptions();
@@ -56,7 +63,7 @@ public function testShouldHaveExpectedOptions()
public function testShouldHaveExpectedAttributes()
{
- $command = new SetupBrokerCommand($this->createMock(ContainerInterface::class));
+ $command = new SetupBrokerCommand($this->createMock(ContainerInterface::class), 'default');
$arguments = $command->getDefinition()->getArguments();
@@ -73,12 +80,12 @@ public function testShouldCallDriverSetupBrokerMethod()
$command = new SetupBrokerCommand(new Container([
'enqueue.client.default.driver' => $driver,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([]);
- $this->assertContains('Broker set up', $tester->getDisplay());
+ $this->assertStringContainsString('Broker set up', $tester->getDisplay());
}
public function testShouldCallRequestedClientDriverSetupBrokerMethod()
@@ -98,14 +105,14 @@ public function testShouldCallRequestedClientDriverSetupBrokerMethod()
$command = new SetupBrokerCommand(new Container([
'enqueue.client.default.driver' => $defaultDriver,
'enqueue.client.foo.driver' => $fooDriver,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
'--client' => 'foo',
]);
- $this->assertContains('Broker set up', $tester->getDisplay());
+ $this->assertStringContainsString('Broker set up', $tester->getDisplay());
}
public function testShouldThrowIfClientNotFound()
@@ -118,7 +125,7 @@ public function testShouldThrowIfClientNotFound()
$command = new SetupBrokerCommand(new Container([
'enqueue.client.default.driver' => $defaultDriver,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -130,7 +137,7 @@ public function testShouldThrowIfClientNotFound()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|DriverInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|DriverInterface
*/
private function createClientDriverMock()
{
diff --git a/pkg/enqueue/Tests/Symfony/Client/SimpleConsumeCommandTest.php b/pkg/enqueue/Tests/Symfony/Client/SimpleConsumeCommandTest.php
new file mode 100644
index 000000000..21c491eb5
--- /dev/null
+++ b/pkg/enqueue/Tests/Symfony/Client/SimpleConsumeCommandTest.php
@@ -0,0 +1,130 @@
+assertClassExtends(ConsumeCommand::class, SimpleConsumeCommand::class);
+ }
+
+ public function testShouldNotBeFinal()
+ {
+ $this->assertClassNotFinal(SimpleConsumeCommand::class);
+ }
+
+ public function testShouldHaveExpectedOptions()
+ {
+ $command = new SimpleConsumeCommand($this->createQueueConsumerMock(), $this->createDriverStub(), $this->createDelegateProcessorMock());
+
+ $options = $command->getDefinition()->getOptions();
+
+ $this->assertCount(9, $options);
+ $this->assertArrayHasKey('memory-limit', $options);
+ $this->assertArrayHasKey('message-limit', $options);
+ $this->assertArrayHasKey('time-limit', $options);
+ $this->assertArrayHasKey('receive-timeout', $options);
+ $this->assertArrayHasKey('niceness', $options);
+ $this->assertArrayHasKey('client', $options);
+ $this->assertArrayHasKey('logger', $options);
+ $this->assertArrayHasKey('skip', $options);
+ $this->assertArrayHasKey('setup-broker', $options);
+ }
+
+ public function testShouldHaveExpectedAttributes()
+ {
+ $command = new SimpleConsumeCommand($this->createQueueConsumerMock(), $this->createDriverStub(), $this->createDelegateProcessorMock());
+
+ $arguments = $command->getDefinition()->getArguments();
+
+ $this->assertCount(1, $arguments);
+ $this->assertArrayHasKey('client-queue-names', $arguments);
+ }
+
+ public function testShouldBindDefaultQueueOnly()
+ {
+ $queue = new NullQueue('');
+
+ $routeCollection = new RouteCollection([]);
+
+ $processor = $this->createDelegateProcessorMock();
+
+ $consumer = $this->createQueueConsumerMock();
+ $consumer
+ ->expects($this->once())
+ ->method('bind')
+ ->with($this->identicalTo($queue), $this->identicalTo($processor))
+ ;
+ $consumer
+ ->expects($this->once())
+ ->method('consume')
+ ->with($this->isInstanceOf(ChainExtension::class))
+ ;
+
+ $driver = $this->createDriverStub($routeCollection);
+ $driver
+ ->expects($this->once())
+ ->method('createQueue')
+ ->with('default', true)
+ ->willReturn($queue)
+ ;
+
+ $command = new SimpleConsumeCommand($consumer, $driver, $processor);
+
+ $tester = new CommandTester($command);
+ $tester->execute([]);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|DelegateProcessor
+ */
+ private function createDelegateProcessorMock()
+ {
+ return $this->createMock(DelegateProcessor::class);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|QueueConsumerInterface
+ */
+ private function createQueueConsumerMock()
+ {
+ return $this->createMock(QueueConsumerInterface::class);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|DriverInterface
+ */
+ private function createDriverStub(?RouteCollection $routeCollection = null): DriverInterface
+ {
+ $driverMock = $this->createMock(DriverInterface::class);
+ $driverMock
+ ->expects($this->any())
+ ->method('getRouteCollection')
+ ->willReturn($routeCollection ?? new RouteCollection([]))
+ ;
+
+ $driverMock
+ ->expects($this->any())
+ ->method('getConfig')
+ ->willReturn(Config::create('aPrefix', 'anApp'))
+ ;
+
+ return $driverMock;
+ }
+}
diff --git a/pkg/enqueue/Tests/Symfony/Client/SimpleProduceCommandTest.php b/pkg/enqueue/Tests/Symfony/Client/SimpleProduceCommandTest.php
new file mode 100644
index 000000000..3ff81bfd5
--- /dev/null
+++ b/pkg/enqueue/Tests/Symfony/Client/SimpleProduceCommandTest.php
@@ -0,0 +1,78 @@
+assertClassExtends(ProduceCommand::class, SimpleProduceCommand::class);
+ }
+
+ public function testShouldNotBeFinal()
+ {
+ $this->assertClassNotFinal(SimpleProduceCommand::class);
+ }
+
+ public function testShouldHaveExpectedOptions()
+ {
+ $command = new SimpleProduceCommand($this->createProducerMock());
+
+ $options = $command->getDefinition()->getOptions();
+ $this->assertCount(4, $options);
+ $this->assertArrayHasKey('client', $options);
+ $this->assertArrayHasKey('topic', $options);
+ $this->assertArrayHasKey('command', $options);
+ $this->assertArrayHasKey('header', $options);
+ }
+
+ public function testShouldHaveExpectedAttributes()
+ {
+ $command = new SimpleProduceCommand($this->createProducerMock());
+
+ $arguments = $command->getDefinition()->getArguments();
+ $this->assertCount(1, $arguments);
+
+ $this->assertArrayHasKey('message', $arguments);
+ }
+
+ public function testThrowIfNeitherTopicNorCommandOptionsAreSet()
+ {
+ $producerMock = $this->createProducerMock();
+ $producerMock
+ ->expects($this->never())
+ ->method('sendEvent')
+ ;
+ $producerMock
+ ->expects($this->never())
+ ->method('sendCommand')
+ ;
+
+ $command = new SimpleProduceCommand($producerMock);
+
+ $tester = new CommandTester($command);
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Either topic or command option should be set, none is set.');
+ $tester->execute([
+ 'message' => 'theMessage',
+ ]);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|ProducerInterface
+ */
+ private function createProducerMock()
+ {
+ return $this->createMock(ProducerInterface::class);
+ }
+}
diff --git a/pkg/enqueue/Tests/Symfony/Client/SimpleRoutesCommandTest.php b/pkg/enqueue/Tests/Symfony/Client/SimpleRoutesCommandTest.php
new file mode 100644
index 000000000..20ee454cc
--- /dev/null
+++ b/pkg/enqueue/Tests/Symfony/Client/SimpleRoutesCommandTest.php
@@ -0,0 +1,107 @@
+assertClassExtends(RoutesCommand::class, SimpleRoutesCommand::class);
+ }
+
+ public function testShouldNotBeFinal()
+ {
+ $this->assertClassNotFinal(SimpleRoutesCommand::class);
+ }
+
+ public function testShouldHaveCommandAliases()
+ {
+ $command = new SimpleRoutesCommand($this->createDriverMock());
+
+ $this->assertEquals(['debug:enqueue:routes'], $command->getAliases());
+ }
+
+ public function testShouldHaveExpectedOptions()
+ {
+ $command = new SimpleRoutesCommand($this->createDriverMock());
+
+ $options = $command->getDefinition()->getOptions();
+ $this->assertCount(2, $options);
+
+ $this->assertArrayHasKey('show-route-options', $options);
+ $this->assertArrayHasKey('client', $options);
+ }
+
+ public function testShouldHaveExpectedAttributes()
+ {
+ $command = new SimpleRoutesCommand($this->createDriverMock());
+
+ $arguments = $command->getDefinition()->getArguments();
+ $this->assertCount(0, $arguments);
+ }
+
+ public function testShouldOutputEmptyRouteCollection()
+ {
+ $routeCollection = new RouteCollection([]);
+
+ $command = new SimpleRoutesCommand($this->createDriverStub(Config::create(), $routeCollection));
+
+ $tester = new CommandTester($command);
+
+ $tester->execute([]);
+
+ $expectedOutput = <<<'OUTPUT'
+Found 0 routes
+
+
+OUTPUT;
+
+ $this->assertCommandOutput($expectedOutput, $tester);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject
+ */
+ private function createDriverMock(): DriverInterface
+ {
+ return $this->createMock(DriverInterface::class);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject
+ */
+ private function createDriverStub(Config $config, RouteCollection $routeCollection): DriverInterface
+ {
+ $driverMock = $this->createDriverMock();
+ $driverMock
+ ->expects($this->any())
+ ->method('getConfig')
+ ->willReturn($config)
+ ;
+
+ $driverMock
+ ->expects($this->any())
+ ->method('getRouteCollection')
+ ->willReturn($routeCollection)
+ ;
+
+ return $driverMock;
+ }
+
+ private function assertCommandOutput(string $expected, CommandTester $tester): void
+ {
+ $this->assertSame(0, $tester->getStatusCode());
+ $this->assertSame($expected, $tester->getDisplay());
+ }
+}
diff --git a/pkg/enqueue/Tests/Symfony/Client/SimpleSetupBrokerCommandTest.php b/pkg/enqueue/Tests/Symfony/Client/SimpleSetupBrokerCommandTest.php
new file mode 100644
index 000000000..3702dbf18
--- /dev/null
+++ b/pkg/enqueue/Tests/Symfony/Client/SimpleSetupBrokerCommandTest.php
@@ -0,0 +1,75 @@
+assertClassExtends(SetupBrokerCommand::class, SimpleSetupBrokerCommand::class);
+ }
+
+ public function testShouldNotBeFinal()
+ {
+ $this->assertClassNotFinal(SimpleSetupBrokerCommand::class);
+ }
+
+ public function testShouldHaveCommandAliases()
+ {
+ $command = new SimpleSetupBrokerCommand($this->createClientDriverMock());
+
+ $this->assertEquals(['enq:sb'], $command->getAliases());
+ }
+
+ public function testShouldHaveExpectedOptions()
+ {
+ $command = new SimpleSetupBrokerCommand($this->createClientDriverMock());
+
+ $options = $command->getDefinition()->getOptions();
+
+ $this->assertCount(1, $options);
+ $this->assertArrayHasKey('client', $options);
+ }
+
+ public function testShouldHaveExpectedAttributes()
+ {
+ $command = new SimpleSetupBrokerCommand($this->createClientDriverMock());
+
+ $arguments = $command->getDefinition()->getArguments();
+
+ $this->assertCount(0, $arguments);
+ }
+
+ public function testShouldCallDriverSetupBrokerMethod()
+ {
+ $driver = $this->createClientDriverMock();
+ $driver
+ ->expects($this->once())
+ ->method('setupBroker')
+ ;
+
+ $command = new SimpleSetupBrokerCommand($driver);
+
+ $tester = new CommandTester($command);
+ $tester->execute([]);
+
+ $this->assertStringContainsString('Broker set up', $tester->getDisplay());
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|DriverInterface
+ */
+ private function createClientDriverMock()
+ {
+ return $this->createMock(DriverInterface::class);
+ }
+}
diff --git a/pkg/enqueue/Tests/Symfony/Consumption/ConfigurableConsumeCommandTest.php b/pkg/enqueue/Tests/Symfony/Consumption/ConfigurableConsumeCommandTest.php
index b402960ac..251e264e2 100644
--- a/pkg/enqueue/Tests/Symfony/Consumption/ConfigurableConsumeCommandTest.php
+++ b/pkg/enqueue/Tests/Symfony/Consumption/ConfigurableConsumeCommandTest.php
@@ -15,6 +15,7 @@
use Interop\Queue\Queue as InteropQueue;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;
@@ -32,21 +33,27 @@ public function testShouldNotBeFinal()
$this->assertClassNotFinal(ConfigurableConsumeCommand::class);
}
- public function testCouldBeConstructedWithRequiredAttributes()
+ public function testShouldHaveAsCommandAttributeWithCommandName()
{
- new ConfigurableConsumeCommand($this->createMock(ContainerInterface::class));
- }
+ $commandClass = ConfigurableConsumeCommand::class;
- public function testShouldHaveCommandName()
- {
- $command = new ConfigurableConsumeCommand($this->createMock(ContainerInterface::class));
+ $reflectionClass = new \ReflectionClass($commandClass);
+
+ $attributes = $reflectionClass->getAttributes(AsCommand::class);
+
+ $this->assertNotEmpty($attributes, 'The command does not have the AsCommand attribute.');
+
+ // Get the first attribute instance (assuming there is only one AsCommand attribute)
+ $asCommandAttribute = $attributes[0];
- $this->assertEquals('enqueue:transport:consume', $command->getName());
+ // Verify the 'name' parameter value
+ $attributeInstance = $asCommandAttribute->newInstance();
+ $this->assertEquals('enqueue:transport:consume', $attributeInstance->name, 'The command name is not set correctly in the AsCommand attribute.');
}
public function testShouldHaveExpectedOptions()
{
- $command = new ConfigurableConsumeCommand($this->createMock(ContainerInterface::class));
+ $command = new ConfigurableConsumeCommand($this->createMock(ContainerInterface::class), 'default');
$options = $command->getDefinition()->getOptions();
@@ -62,7 +69,7 @@ public function testShouldHaveExpectedOptions()
public function testShouldHaveExpectedAttributes()
{
- $command = new ConfigurableConsumeCommand($this->createMock(ContainerInterface::class));
+ $command = new ConfigurableConsumeCommand($this->createMock(ContainerInterface::class), 'default');
$arguments = $command->getDefinition()->getArguments();
@@ -88,7 +95,7 @@ public function testThrowIfNeitherQueueOptionNorProcessorImplementsQueueSubscrib
$command = new ConfigurableConsumeCommand(new Container([
'enqueue.transport.default.queue_consumer' => $consumer,
'enqueue.transport.default.processor_registry' => new ArrayProcessorRegistry(['aProcessor' => $processor]),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -118,7 +125,7 @@ public function testShouldExecuteConsumptionWithExplicitlySetQueue()
$command = new ConfigurableConsumeCommand(new Container([
'enqueue.transport.default.queue_consumer' => $consumer,
'enqueue.transport.default.processor_registry' => new ArrayProcessorRegistry(['processor-service' => $processor]),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
@@ -144,7 +151,7 @@ public function testThrowIfTransportNotDefined()
$command = new ConfigurableConsumeCommand(new Container([
'enqueue.transport.default.queue_consumer' => $consumer,
'enqueue.transport.default.processor_registry' => new ArrayProcessorRegistry(['processor-service' => $processor]),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -181,7 +188,7 @@ public function testShouldExecuteConsumptionWithSeveralCustomQueues()
$command = new ConfigurableConsumeCommand(new Container([
'enqueue.transport.default.queue_consumer' => $consumer,
'enqueue.transport.default.processor_registry' => new ArrayProcessorRegistry(['processor-service' => $processor]),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
@@ -192,8 +199,8 @@ public function testShouldExecuteConsumptionWithSeveralCustomQueues()
public function testShouldExecuteConsumptionWhenProcessorImplementsQueueSubscriberInterface()
{
- $processor = new class() implements Processor, QueueSubscriberInterface {
- public function process(InteropMessage $message, Context $context)
+ $processor = new class implements Processor, QueueSubscriberInterface {
+ public function process(InteropMessage $message, Context $context): void
{
}
@@ -223,7 +230,7 @@ public static function getSubscribedQueues()
$command = new ConfigurableConsumeCommand(new Container([
'enqueue.transport.default.queue_consumer' => $consumer,
'enqueue.transport.default.processor_registry' => new ArrayProcessorRegistry(['processor-service' => $processor]),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
@@ -263,7 +270,7 @@ public function testShouldExecuteConsumptionWithCustomTransportExplicitlySetQueu
'enqueue.transport.foo.processor_registry' => new ArrayProcessorRegistry(['processor-service' => $processor]),
'enqueue.transport.bar.queue_consumer' => $barConsumer,
'enqueue.transport.bar.processor_registry' => new ArrayProcessorRegistry(['processor-service' => $processor]),
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([
@@ -274,7 +281,7 @@ public function testShouldExecuteConsumptionWithCustomTransportExplicitlySetQueu
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|InteropQueue
+ * @return \PHPUnit\Framework\MockObject\MockObject|InteropQueue
*/
protected function createQueueMock()
{
@@ -282,7 +289,7 @@ protected function createQueueMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Processor
+ * @return \PHPUnit\Framework\MockObject\MockObject|Processor
*/
protected function createProcessor()
{
@@ -290,7 +297,7 @@ protected function createProcessor()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|QueueConsumerInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|QueueConsumerInterface
*/
protected function createQueueConsumerMock()
{
diff --git a/pkg/enqueue/Tests/Symfony/Consumption/ConsumeCommandTest.php b/pkg/enqueue/Tests/Symfony/Consumption/ConsumeCommandTest.php
index a8ead2d8e..f07bef03b 100644
--- a/pkg/enqueue/Tests/Symfony/Consumption/ConsumeCommandTest.php
+++ b/pkg/enqueue/Tests/Symfony/Consumption/ConsumeCommandTest.php
@@ -3,12 +3,21 @@
namespace Enqueue\Tests\Symfony\Consumption;
use Enqueue\Consumption\ChainExtension;
+use Enqueue\Consumption\Context\Start;
+use Enqueue\Consumption\ExtensionInterface;
+use Enqueue\Consumption\QueueConsumer;
use Enqueue\Consumption\QueueConsumerInterface;
use Enqueue\Container\Container;
+use Enqueue\Null\NullQueue;
use Enqueue\Symfony\Consumption\ConsumeCommand;
use Enqueue\Test\ClassExtensionTrait;
+use Interop\Queue\Consumer;
+use Interop\Queue\Context as InteropContext;
+use Interop\Queue\Exception\SubscriptionConsumerNotSupportedException;
+use Interop\Queue\Queue;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
+use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;
@@ -26,21 +35,27 @@ public function testShouldNotBeFinal()
$this->assertClassNotFinal(ConsumeCommand::class);
}
- public function testCouldBeConstructedWithRequiredAttributes()
+ public function testShouldHaveAsCommandAttributeWithCommandName()
{
- new ConsumeCommand($this->createMock(ContainerInterface::class));
- }
+ $commandClass = ConsumeCommand::class;
- public function testShouldHaveCommandName()
- {
- $command = new ConsumeCommand($this->createMock(ContainerInterface::class));
+ $reflectionClass = new \ReflectionClass($commandClass);
+
+ $attributes = $reflectionClass->getAttributes(AsCommand::class);
- $this->assertEquals('enqueue:transport:consume', $command->getName());
+ $this->assertNotEmpty($attributes, 'The command does not have the AsCommand attribute.');
+
+ // Get the first attribute instance (assuming there is only one AsCommand attribute)
+ $asCommandAttribute = $attributes[0];
+
+ // Verify the 'name' parameter value
+ $attributeInstance = $asCommandAttribute->newInstance();
+ $this->assertEquals('enqueue:transport:consume', $attributeInstance->name, 'The command name is not set correctly in the AsCommand attribute.');
}
public function testShouldHaveExpectedOptions()
{
- $command = new ConsumeCommand($this->createMock(ContainerInterface::class));
+ $command = new ConsumeCommand($this->createMock(ContainerInterface::class), 'default');
$options = $command->getDefinition()->getOptions();
@@ -56,7 +71,7 @@ public function testShouldHaveExpectedOptions()
public function testShouldHaveExpectedAttributes()
{
- $command = new ConsumeCommand($this->createMock(ContainerInterface::class));
+ $command = new ConsumeCommand($this->createMock(ContainerInterface::class), 'default');
$arguments = $command->getDefinition()->getArguments();
@@ -74,7 +89,7 @@ public function testShouldExecuteDefaultConsumption()
$command = new ConsumeCommand(new Container([
'enqueue.transport.default.queue_consumer' => $consumer,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute([]);
@@ -98,7 +113,7 @@ public function testShouldExecuteCustomConsumption()
$command = new ConsumeCommand(new Container([
'enqueue.transport.default.queue_consumer' => $defaultConsumer,
'enqueue.transport.custom.queue_consumer' => $customConsumer,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
$tester->execute(['--transport' => 'custom']);
@@ -114,7 +129,7 @@ public function testThrowIfNotDefinedTransportRequested()
$command = new ConsumeCommand(new Container([
'enqueue.transport.default.queue_consumer' => $defaultConsumer,
- ]));
+ ]), 'default');
$tester = new CommandTester($command);
@@ -123,11 +138,110 @@ public function testThrowIfNotDefinedTransportRequested()
$tester->execute(['--transport' => 'not-defined']);
}
+ public function testShouldReturnExitStatusIfSet()
+ {
+ $testExitCode = 678;
+
+ $stubExtension = $this->createExtension();
+
+ $stubExtension
+ ->expects($this->once())
+ ->method('onStart')
+ ->with($this->isInstanceOf(Start::class))
+ ->willReturnCallback(function (Start $context) use ($testExitCode) {
+ $context->interruptExecution($testExitCode);
+ })
+ ;
+
+ $consumer = new QueueConsumer($this->createContextStub(), $stubExtension);
+
+ $command = new ConsumeCommand(new Container([
+ 'enqueue.transport.default.queue_consumer' => $consumer,
+ ]), 'default');
+
+ $tester = new CommandTester($command);
+
+ $tester->execute([]);
+
+ $this->assertEquals($testExitCode, $tester->getStatusCode());
+ }
+
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|QueueConsumerInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|QueueConsumerInterface
*/
private function createQueueConsumerMock()
{
return $this->createMock(QueueConsumerInterface::class);
}
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject
+ */
+ private function createContextWithoutSubscriptionConsumerMock(): InteropContext
+ {
+ $contextMock = $this->createMock(InteropContext::class);
+ $contextMock
+ ->expects($this->any())
+ ->method('createSubscriptionConsumer')
+ ->willThrowException(SubscriptionConsumerNotSupportedException::providerDoestNotSupportIt())
+ ;
+
+ return $contextMock;
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|InteropContext
+ */
+ private function createContextStub(?Consumer $consumer = null): InteropContext
+ {
+ $context = $this->createContextWithoutSubscriptionConsumerMock();
+ $context
+ ->expects($this->any())
+ ->method('createQueue')
+ ->willReturnCallback(function (string $queueName) {
+ return new NullQueue($queueName);
+ })
+ ;
+ $context
+ ->expects($this->any())
+ ->method('createConsumer')
+ ->willReturnCallback(function (Queue $queue) use ($consumer) {
+ return $consumer ?: $this->createConsumerStub($queue);
+ })
+ ;
+
+ return $context;
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|ExtensionInterface
+ */
+ private function createExtension()
+ {
+ return $this->createMock(ExtensionInterface::class);
+ }
+
+ /**
+ * @param mixed|null $queue
+ *
+ * @return \PHPUnit\Framework\MockObject\MockObject|Consumer
+ */
+ private function createConsumerStub($queue = null): Consumer
+ {
+ if (null === $queue) {
+ $queue = 'queue';
+ }
+ if (is_string($queue)) {
+ $queue = new NullQueue($queue);
+ }
+
+ $consumerMock = $this->createMock(Consumer::class);
+ $consumerMock
+ ->expects($this->any())
+ ->method('getQueue')
+ ->willReturn($queue)
+ ;
+
+ return $consumerMock;
+ }
}
diff --git a/pkg/enqueue/Tests/Symfony/Consumption/LimitsExtensionsCommandTraitTest.php b/pkg/enqueue/Tests/Symfony/Consumption/LimitsExtensionsCommandTraitTest.php
index 54952749a..f47a32161 100644
--- a/pkg/enqueue/Tests/Symfony/Consumption/LimitsExtensionsCommandTraitTest.php
+++ b/pkg/enqueue/Tests/Symfony/Consumption/LimitsExtensionsCommandTraitTest.php
@@ -108,17 +108,35 @@ public function testShouldAddThreeLimitExtensions()
$this->assertInstanceOf(LimitConsumerMemoryExtension::class, $result[2]);
}
- public function testShouldAddNicenessExtension()
+ /**
+ * @dataProvider provideNicenessValues
+ */
+ public function testShouldAddNicenessExtension($inputValue, bool $enabled)
{
$command = new LimitsExtensionsCommand('name');
$tester = new CommandTester($command);
$tester->execute([
- '--niceness' => 1,
+ '--niceness' => $inputValue,
]);
$result = $command->getExtensions();
- $this->assertCount(1, $result);
- $this->assertInstanceOf(NicenessExtension::class, $result[0]);
+ if ($enabled) {
+ $this->assertCount(1, $result);
+ $this->assertInstanceOf(NicenessExtension::class, $result[0]);
+ } else {
+ $this->assertEmpty($result);
+ }
+ }
+
+ public function provideNicenessValues(): \Generator
+ {
+ yield [1, true];
+ yield ['1', true];
+ yield [-1.0, true];
+ yield ['100', true];
+ yield ['', false];
+ yield ['0', false];
+ yield [0.0, false];
}
}
diff --git a/pkg/enqueue/Tests/Symfony/Consumption/Mock/LimitsExtensionsCommand.php b/pkg/enqueue/Tests/Symfony/Consumption/Mock/LimitsExtensionsCommand.php
index 7b6722393..b15fe82fd 100644
--- a/pkg/enqueue/Tests/Symfony/Consumption/Mock/LimitsExtensionsCommand.php
+++ b/pkg/enqueue/Tests/Symfony/Consumption/Mock/LimitsExtensionsCommand.php
@@ -18,15 +18,17 @@ public function getExtensions()
return $this->extensions;
}
- protected function configure()
+ protected function configure(): void
{
parent::configure();
$this->configureLimitsExtensions();
}
- protected function execute(InputInterface $input, OutputInterface $output)
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->extensions = $this->getLimitsExtensions($input, $output);
+
+ return 0;
}
}
diff --git a/pkg/enqueue/Tests/Symfony/Consumption/Mock/QueueConsumerOptionsCommand.php b/pkg/enqueue/Tests/Symfony/Consumption/Mock/QueueConsumerOptionsCommand.php
index 289a5e711..55aa0ab48 100644
--- a/pkg/enqueue/Tests/Symfony/Consumption/Mock/QueueConsumerOptionsCommand.php
+++ b/pkg/enqueue/Tests/Symfony/Consumption/Mock/QueueConsumerOptionsCommand.php
@@ -24,15 +24,17 @@ public function __construct(QueueConsumerInterface $consumer)
$this->consumer = $consumer;
}
- protected function configure()
+ protected function configure(): void
{
parent::configure();
$this->configureQueueConsumerOptions();
}
- protected function execute(InputInterface $input, OutputInterface $output)
+ protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->setQueueConsumerOptions($this->consumer, $input);
+
+ return 0;
}
}
diff --git a/pkg/enqueue/Tests/Symfony/Consumption/Mock/QueueSubscriberProcessor.php b/pkg/enqueue/Tests/Symfony/Consumption/Mock/QueueSubscriberProcessor.php
index 56b3c9319..a210b0e6b 100644
--- a/pkg/enqueue/Tests/Symfony/Consumption/Mock/QueueSubscriberProcessor.php
+++ b/pkg/enqueue/Tests/Symfony/Consumption/Mock/QueueSubscriberProcessor.php
@@ -11,6 +11,7 @@ class QueueSubscriberProcessor implements Processor, QueueSubscriberInterface
{
public function process(InteropMessage $message, Context $context)
{
+ return self::ACK;
}
public static function getSubscribedQueues()
diff --git a/pkg/enqueue/Tests/Symfony/Consumption/QueueConsumerOptionsCommandTraitTest.php b/pkg/enqueue/Tests/Symfony/Consumption/QueueConsumerOptionsCommandTraitTest.php
index c221f0284..b44c89af9 100644
--- a/pkg/enqueue/Tests/Symfony/Consumption/QueueConsumerOptionsCommandTraitTest.php
+++ b/pkg/enqueue/Tests/Symfony/Consumption/QueueConsumerOptionsCommandTraitTest.php
@@ -37,7 +37,7 @@ public function testShouldSetQueueConsumerOptions()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|QueueConsumerInterface
+ * @return \PHPUnit\Framework\MockObject\MockObject|QueueConsumerInterface
*/
private function createQueueConsumer()
{
diff --git a/pkg/enqueue/Tests/Symfony/Consumption/SimpleConsumeCommandTest.php b/pkg/enqueue/Tests/Symfony/Consumption/SimpleConsumeCommandTest.php
new file mode 100644
index 000000000..eeb38bf19
--- /dev/null
+++ b/pkg/enqueue/Tests/Symfony/Consumption/SimpleConsumeCommandTest.php
@@ -0,0 +1,74 @@
+assertClassExtends(ConsumeCommand::class, SimpleConsumeCommand::class);
+ }
+
+ public function testShouldNotBeFinal()
+ {
+ $this->assertClassNotFinal(SimpleConsumeCommand::class);
+ }
+
+ public function testShouldHaveExpectedOptions()
+ {
+ $command = new SimpleConsumeCommand($this->createQueueConsumerMock());
+
+ $options = $command->getDefinition()->getOptions();
+
+ $this->assertCount(7, $options);
+ $this->assertArrayHasKey('memory-limit', $options);
+ $this->assertArrayHasKey('message-limit', $options);
+ $this->assertArrayHasKey('time-limit', $options);
+ $this->assertArrayHasKey('receive-timeout', $options);
+ $this->assertArrayHasKey('niceness', $options);
+ $this->assertArrayHasKey('transport', $options);
+ $this->assertArrayHasKey('logger', $options);
+ }
+
+ public function testShouldHaveExpectedAttributes()
+ {
+ $command = new SimpleConsumeCommand($this->createQueueConsumerMock());
+
+ $arguments = $command->getDefinition()->getArguments();
+
+ $this->assertCount(0, $arguments);
+ }
+
+ public function testShouldExecuteDefaultConsumption()
+ {
+ $consumer = $this->createQueueConsumerMock();
+ $consumer
+ ->expects($this->once())
+ ->method('consume')
+ ->with($this->isInstanceOf(ChainExtension::class))
+ ;
+
+ $command = new SimpleConsumeCommand($consumer);
+
+ $tester = new CommandTester($command);
+ $tester->execute([]);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|QueueConsumerInterface
+ */
+ private function createQueueConsumerMock()
+ {
+ return $this->createMock(QueueConsumerInterface::class);
+ }
+}
diff --git a/pkg/enqueue/Tests/Symfony/ContainerProcessorRegistryTest.php b/pkg/enqueue/Tests/Symfony/ContainerProcessorRegistryTest.php
index bb3cacb53..5504e8ef6 100644
--- a/pkg/enqueue/Tests/Symfony/ContainerProcessorRegistryTest.php
+++ b/pkg/enqueue/Tests/Symfony/ContainerProcessorRegistryTest.php
@@ -23,11 +23,6 @@ public function testShouldBeFinal()
$this->assertClassFinal(ContainerProcessorRegistry::class);
}
- public function testCouldBeConstructedWithContainerAsFirstArgument()
- {
- new ContainerProcessorRegistry($this->createContainerMock());
- }
-
public function testShouldAllowGetProcessor()
{
$processorMock = $this->createProcessorMock();
@@ -69,7 +64,11 @@ public function testThrowErrorIfServiceDoesNotImplementProcessorReturnType()
$registry = new ContainerProcessorRegistry($containerMock);
$this->expectException(\TypeError::class);
- $this->expectExceptionMessage('Return value of Enqueue\Symfony\ContainerProcessorRegistry::get() must implement interface Interop\Queue\Processor, instance of stdClass returned');
+ // Exception messages vary slightly between versions
+ $this->expectExceptionMessageMatches(
+ '/Enqueue\\\\Symfony\\\\ContainerProcessorRegistry::get\(\).+ Interop\\\\Queue\\\\Processor,.*stdClass returned/'
+ );
+
$registry->get('processor-name');
}
@@ -91,7 +90,7 @@ public function testShouldThrowExceptionIfProcessorIsNotSet()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createProcessorMock(): Processor
{
@@ -99,7 +98,7 @@ private function createProcessorMock(): Processor
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return \PHPUnit\Framework\MockObject\MockObject
*/
private function createContainerMock(): ContainerInterface
{
diff --git a/pkg/enqueue/Tests/Symfony/DependencyInjection/BuildConsumptionExtensionsPassTest.php b/pkg/enqueue/Tests/Symfony/DependencyInjection/BuildConsumptionExtensionsPassTest.php
index 6a7e83fac..bdccd338c 100644
--- a/pkg/enqueue/Tests/Symfony/DependencyInjection/BuildConsumptionExtensionsPassTest.php
+++ b/pkg/enqueue/Tests/Symfony/DependencyInjection/BuildConsumptionExtensionsPassTest.php
@@ -25,28 +25,25 @@ public function testShouldBeFinal()
$this->assertClassFinal(BuildConsumptionExtensionsPass::class);
}
- public function testCouldBeConstructedWithName()
+ public function testThrowIfEnqueueTransportsParameterNotSet()
{
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $pass = new BuildConsumptionExtensionsPass();
- $this->assertAttributeSame('aName', 'name', $pass);
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The "enqueue.transports" parameter must be set.');
+ $pass->process(new ContainerBuilder());
}
- public function testThrowIfNameEmptyOnConstruct()
- {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The name could not be empty.');
- new BuildConsumptionExtensionsPass('');
- }
-
- public function testShouldDoNothingIfExtensionsServiceIsNotRegistered()
+ public function testThrowsIfNoConsumptionExtensionsServiceFoundForConfiguredTransport()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.transports', ['foo', 'bar']);
+ $container->setParameter('enqueue.default_transport', 'foo');
- //guard
- $this->assertFalse($container->hasDefinition('enqueue.transport.aName.consumption_extensions'));
+ $pass = new BuildConsumptionExtensionsPass();
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Service "enqueue.transport.foo.consumption_extensions" not found');
$pass->process($container);
}
@@ -56,19 +53,21 @@ public function testShouldRegisterTransportExtension()
$extensions->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.transport.aName.consumption_extensions', $extensions);
+ $container->setParameter('enqueue.transports', ['foo']);
+ $container->setParameter('enqueue.default_transport', 'foo');
+ $container->setDefinition('enqueue.transport.foo.consumption_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
- ->addTag('enqueue.transport.consumption_extension', ['transport' => 'aName'])
+ ->addTag('enqueue.transport.consumption_extension', ['transport' => 'foo'])
;
$container->register('aBarExtension', ExtensionInterface::class)
- ->addTag('enqueue.transport.consumption_extension', ['transport' => 'aName'])
+ ->addTag('enqueue.transport.consumption_extension', ['transport' => 'foo'])
;
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
new Reference('aBarExtension'),
@@ -81,19 +80,21 @@ public function testShouldIgnoreOtherTransportExtensions()
$extensions->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.transport.aName.consumption_extensions', $extensions);
+ $container->setParameter('enqueue.transports', ['foo']);
+ $container->setParameter('enqueue.default_transport', 'foo');
+ $container->setDefinition('enqueue.transport.foo.consumption_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
- ->addTag('enqueue.transport.consumption_extension', ['transport' => 'aName'])
+ ->addTag('enqueue.transport.consumption_extension', ['transport' => 'foo'])
;
$container->register('aBarExtension', ExtensionInterface::class)
->addTag('enqueue.transport.consumption_extension', ['transport' => 'anotherName'])
;
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
], $extensions->getArgument(0));
@@ -105,7 +106,9 @@ public function testShouldAddExtensionIfTransportAll()
$extensions->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.transport.aName.consumption_extensions', $extensions);
+ $container->setParameter('enqueue.transports', ['foo']);
+ $container->setParameter('enqueue.default_transport', 'foo');
+ $container->setDefinition('enqueue.transport.foo.consumption_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
->addTag('enqueue.transport.consumption_extension', ['transport' => 'all'])
@@ -114,10 +117,10 @@ public function testShouldAddExtensionIfTransportAll()
->addTag('enqueue.transport.consumption_extension', ['transport' => 'anotherName'])
;
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
], $extensions->getArgument(0));
@@ -129,7 +132,9 @@ public function testShouldTreatTagsWithoutTransportAsDefaultTransport()
$extensions->addArgument([]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.transport.default.consumption_extensions', $extensions);
+ $container->setParameter('enqueue.transports', ['foo']);
+ $container->setParameter('enqueue.default_transport', 'foo');
+ $container->setDefinition('enqueue.transport.foo.consumption_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
->addTag('enqueue.transport.consumption_extension')
@@ -138,10 +143,10 @@ public function testShouldTreatTagsWithoutTransportAsDefaultTransport()
->addTag('enqueue.transport.consumption_extension')
;
- $pass = new BuildConsumptionExtensionsPass('default');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($extensions->getArgument(0));
$this->assertEquals([
new Reference('aFooExtension'),
new Reference('aBarExtension'),
@@ -151,10 +156,12 @@ public function testShouldTreatTagsWithoutTransportAsDefaultTransport()
public function testShouldOrderExtensionsByPriority()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.transports', ['foo']);
+ $container->setParameter('enqueue.default_transport', 'foo');
$extensions = new Definition();
$extensions->addArgument([]);
- $container->setDefinition('enqueue.transport.default.consumption_extensions', $extensions);
+ $container->setDefinition('enqueue.transport.foo.consumption_extensions', $extensions);
$extension = new Definition();
$extension->addTag('enqueue.transport.consumption_extension', ['priority' => 6]);
@@ -168,7 +175,7 @@ public function testShouldOrderExtensionsByPriority()
$extension->addTag('enqueue.transport.consumption_extension', ['priority' => 2]);
$container->setDefinition('baz_extension', $extension);
- $pass = new BuildConsumptionExtensionsPass('default');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
$orderedExtensions = $extensions->getArgument(0);
@@ -182,10 +189,12 @@ public function testShouldOrderExtensionsByPriority()
public function testShouldAssumePriorityZeroIfPriorityIsNotSet()
{
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.transports', ['foo']);
+ $container->setParameter('enqueue.default_transport', 'foo');
$extensions = new Definition();
$extensions->addArgument([]);
- $container->setDefinition('enqueue.transport.default.consumption_extensions', $extensions);
+ $container->setDefinition('enqueue.transport.foo.consumption_extensions', $extensions);
$extension = new Definition();
$extension->addTag('enqueue.transport.consumption_extension');
@@ -199,7 +208,7 @@ public function testShouldAssumePriorityZeroIfPriorityIsNotSet()
$extension->addTag('enqueue.transport.consumption_extension', ['priority' => -1]);
$container->setDefinition('baz_extension', $extension);
- $pass = new BuildConsumptionExtensionsPass('default');
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
$orderedExtensions = $extensions->getArgument(0);
@@ -219,7 +228,9 @@ public function testShouldMergeWithAddedPreviously()
]);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.transport.aName.consumption_extensions', $extensions);
+ $container->setParameter('enqueue.transports', ['foo']);
+ $container->setParameter('enqueue.default_transport', 'foo');
+ $container->setDefinition('enqueue.transport.foo.consumption_extensions', $extensions);
$container->register('aFooExtension', ExtensionInterface::class)
->addTag('enqueue.transport.consumption_extension')
@@ -228,13 +239,45 @@ public function testShouldMergeWithAddedPreviously()
->addTag('enqueue.transport.consumption_extension')
;
- $pass = new BuildConsumptionExtensionsPass('aName');
+ $pass = new BuildConsumptionExtensionsPass();
+ $pass->process($container);
+
+ self::assertIsArray($extensions->getArgument(0));
+ $this->assertCount(4, $extensions->getArgument(0));
+ }
+
+ public function testShouldRegisterProcessorWithMatchedNameToCorrespondingRegistries()
+ {
+ $fooExtensions = new Definition();
+ $fooExtensions->addArgument([]);
+
+ $barExtensions = new Definition();
+ $barExtensions->addArgument([]);
+
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.transports', ['foo', 'bar']);
+ $container->setParameter('enqueue.default_transport', 'foo');
+ $container->setDefinition('enqueue.transport.foo.consumption_extensions', $fooExtensions);
+ $container->setDefinition('enqueue.transport.bar.consumption_extensions', $barExtensions);
+
+ $container->register('aFooExtension', ExtensionInterface::class)
+ ->addTag('enqueue.transport.consumption_extension', ['transport' => 'foo'])
+ ;
+ $container->register('aBarExtension', ExtensionInterface::class)
+ ->addTag('enqueue.transport.consumption_extension', ['transport' => 'bar'])
+ ;
+
+ $pass = new BuildConsumptionExtensionsPass();
$pass->process($container);
- $this->assertInternalType('array', $extensions->getArgument(0));
+ self::assertIsArray($fooExtensions->getArgument(0));
$this->assertEquals([
- 'aBarExtension' => 'aBarServiceIdAddedPreviously',
- 'aOloloExtension' => 'aOloloServiceIdAddedPreviously',
- ], $extensions->getArgument(0));
+ new Reference('aFooExtension'),
+ ], $fooExtensions->getArgument(0));
+
+ self::assertIsArray($barExtensions->getArgument(0));
+ $this->assertEquals([
+ new Reference('aBarExtension'),
+ ], $barExtensions->getArgument(0));
}
}
diff --git a/pkg/enqueue/Tests/Symfony/DependencyInjection/BuildProcessorRegistryPassTest.php b/pkg/enqueue/Tests/Symfony/DependencyInjection/BuildProcessorRegistryPassTest.php
index 039024f7a..134c216dc 100644
--- a/pkg/enqueue/Tests/Symfony/DependencyInjection/BuildProcessorRegistryPassTest.php
+++ b/pkg/enqueue/Tests/Symfony/DependencyInjection/BuildProcessorRegistryPassTest.php
@@ -26,24 +26,26 @@ public function testShouldBeFinal()
$this->assertClassFinal(BuildProcessorRegistryPass::class);
}
- public function testCouldBeConstructedWithName()
+ public function testThrowIfEnqueueTransportsParameterNotSet()
{
- $pass = new BuildProcessorRegistryPass('aName');
+ $pass = new BuildProcessorRegistryPass();
- $this->assertAttributeSame('aName', 'name', $pass);
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The "enqueue.transports" parameter must be set.');
+ $pass->process(new ContainerBuilder());
}
- public function testThrowIfNameEmptyOnConstruct()
+ public function testThrowsIfNoRegistryServiceFoundForConfiguredTransport()
{
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The name could not be empty.');
- new BuildProcessorRegistryPass('');
- }
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.transports', ['foo', 'bar']);
+ $container->setParameter('enqueue.default_transport', 'baz');
- public function testShouldDoNothingIfProcessorRegistryServiceIsNotRegistered()
- {
- $pass = new BuildProcessorRegistryPass('aName');
- $pass->process(new ContainerBuilder());
+ $pass = new BuildProcessorRegistryPass();
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Service "enqueue.transport.foo.processor_registry" not found');
+ $pass->process($container);
}
public function testShouldRegisterProcessorWithMatchedName()
@@ -52,6 +54,8 @@ public function testShouldRegisterProcessorWithMatchedName()
$registry->addArgument([]);
$container = new ContainerBuilder();
+ $container->setParameter('enqueue.transports', ['foo']);
+ $container->setParameter('enqueue.default_transport', 'foo');
$container->setDefinition('enqueue.transport.foo.processor_registry', $registry);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.transport.processor', ['transport' => 'foo'])
@@ -60,7 +64,7 @@ public function testShouldRegisterProcessorWithMatchedName()
->addTag('enqueue.transport.processor', ['transport' => 'bar'])
;
- $pass = new BuildProcessorRegistryPass('foo');
+ $pass = new BuildProcessorRegistryPass();
$pass->process($container);
@@ -71,13 +75,50 @@ public function testShouldRegisterProcessorWithMatchedName()
]);
}
+ public function testShouldRegisterProcessorWithMatchedNameToCorrespondingRegistries()
+ {
+ $fooRegistry = new Definition(ProcessorRegistryInterface::class);
+ $fooRegistry->addArgument([]);
+
+ $barRegistry = new Definition(ProcessorRegistryInterface::class);
+ $barRegistry->addArgument([]);
+
+ $container = new ContainerBuilder();
+ $container->setParameter('enqueue.transports', ['foo', 'bar']);
+ $container->setParameter('enqueue.default_transport', 'foo');
+ $container->setDefinition('enqueue.transport.foo.processor_registry', $fooRegistry);
+ $container->setDefinition('enqueue.transport.bar.processor_registry', $barRegistry);
+ $container->register('aFooProcessor', 'aProcessorClass')
+ ->addTag('enqueue.transport.processor', ['transport' => 'foo'])
+ ;
+ $container->register('aBarProcessor', 'aProcessorClass')
+ ->addTag('enqueue.transport.processor', ['transport' => 'bar'])
+ ;
+
+ $pass = new BuildProcessorRegistryPass();
+
+ $pass->process($container);
+
+ $this->assertInstanceOf(Reference::class, $fooRegistry->getArgument(0));
+ $this->assertLocatorServices($container, $fooRegistry->getArgument(0), [
+ 'aFooProcessor' => 'aFooProcessor',
+ ]);
+
+ $this->assertInstanceOf(Reference::class, $barRegistry->getArgument(0));
+ $this->assertLocatorServices($container, $barRegistry->getArgument(0), [
+ 'aBarProcessor' => 'aBarProcessor',
+ ]);
+ }
+
public function testShouldRegisterProcessorWithoutNameToDefaultTransport()
{
$registry = new Definition(ProcessorRegistryInterface::class);
$registry->addArgument(null);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.transport.default.processor_registry', $registry);
+ $container->setParameter('enqueue.transports', ['foo']);
+ $container->setParameter('enqueue.default_transport', 'foo');
+ $container->setDefinition('enqueue.transport.foo.processor_registry', $registry);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.transport.processor', [])
;
@@ -85,7 +126,7 @@ public function testShouldRegisterProcessorWithoutNameToDefaultTransport()
->addTag('enqueue.transport.processor', ['transport' => 'bar'])
;
- $pass = new BuildProcessorRegistryPass('default');
+ $pass = new BuildProcessorRegistryPass();
$pass->process($container);
@@ -102,7 +143,9 @@ public function testShouldRegisterProcessorIfTransportNameEqualsAll()
$registry->addArgument(null);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.transport.default.processor_registry', $registry);
+ $container->setParameter('enqueue.transports', ['foo']);
+ $container->setParameter('enqueue.default_transport', 'foo');
+ $container->setDefinition('enqueue.transport.foo.processor_registry', $registry);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.transport.processor', ['transport' => 'all'])
;
@@ -110,7 +153,7 @@ public function testShouldRegisterProcessorIfTransportNameEqualsAll()
->addTag('enqueue.transport.processor', ['transport' => 'bar'])
;
- $pass = new BuildProcessorRegistryPass('default');
+ $pass = new BuildProcessorRegistryPass();
$pass->process($container);
@@ -127,12 +170,14 @@ public function testShouldRegisterWithCustomProcessorName()
$registry->addArgument(null);
$container = new ContainerBuilder();
- $container->setDefinition('enqueue.transport.default.processor_registry', $registry);
+ $container->setParameter('enqueue.transports', ['foo']);
+ $container->setParameter('enqueue.default_transport', 'foo');
+ $container->setDefinition('enqueue.transport.foo.processor_registry', $registry);
$container->register('aFooProcessor', 'aProcessorClass')
->addTag('enqueue.transport.processor', ['processor' => 'customProcessorName'])
;
- $pass = new BuildProcessorRegistryPass('default');
+ $pass = new BuildProcessorRegistryPass();
$pass->process($container);
@@ -149,10 +194,10 @@ private function assertLocatorServices(ContainerBuilder $container, $locatorId,
$locatorId = (string) $locatorId;
$this->assertTrue($container->hasDefinition($locatorId));
- $this->assertRegExp('/service_locator\..*?\.enqueue\./', $locatorId);
+ $this->assertMatchesRegularExpression('/\.?service_locator\..*?\.enqueue\./', $locatorId);
$match = [];
- if (false == preg_match('/(service_locator\..*?)\.enqueue\./', $locatorId, $match)) {
+ if (false == preg_match('/(\.?service_locator\..*?)\.enqueue\./', $locatorId, $match)) {
$this->fail('preg_match should not failed');
}
diff --git a/pkg/enqueue/Tests/Symfony/DependencyInjection/TransportFactoryTest.php b/pkg/enqueue/Tests/Symfony/DependencyInjection/TransportFactoryTest.php
index 64afdc9b4..909407452 100644
--- a/pkg/enqueue/Tests/Symfony/DependencyInjection/TransportFactoryTest.php
+++ b/pkg/enqueue/Tests/Symfony/DependencyInjection/TransportFactoryTest.php
@@ -11,6 +11,7 @@
use Interop\Queue\ConnectionFactory;
use Interop\Queue\Context;
use PHPUnit\Framework\TestCase;
+use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\Definition\Processor;
@@ -27,13 +28,6 @@ public function testShouldBeFinal()
$this->assertClassFinal(TransportFactory::class);
}
- public function testShouldAllowGetNameSetInConstructor()
- {
- $transport = new TransportFactory('aName');
-
- $this->assertEquals('aName', $transport->getName());
- }
-
public function testThrowIfEmptyNameGivenOnConstruction()
{
$this->expectException(\InvalidArgumentException::class);
@@ -44,15 +38,18 @@ public function testThrowIfEmptyNameGivenOnConstruction()
public function testShouldAllowAddConfigurationAsStringDsn()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
+
+ $rootNode->append(TransportFactory::getConfiguration());
- $transport->addTransportConfiguration($rootNode);
$processor = new Processor();
- $config = $processor->process($tb->buildTree(), ['dsn://']);
+ $config = $processor->process($tb->buildTree(), [['transport' => 'dsn://']]);
- $this->assertEquals(['dsn' => 'dsn://'], $config);
+ $this->assertEquals([
+ 'transport' => [
+ 'dsn' => 'dsn://',
+ ],
+ ], $config);
}
/**
@@ -62,191 +59,197 @@ public function testShouldAllowAddConfigurationAsStringDsn()
*/
public function testShouldAllowAddConfigurationAsDsnWithoutSlashes()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
+
+ $rootNode->append(TransportFactory::getConfiguration());
- $transport->addTransportConfiguration($rootNode);
$processor = new Processor();
- $config = $processor->process($tb->buildTree(), ['dsn:']);
+ $config = $processor->process($tb->buildTree(), [['transport' => 'dsn:']]);
- $this->assertEquals(['dsn' => 'dsn:'], $config);
+ $this->assertEquals([
+ 'transport' => [
+ 'dsn' => 'dsn:',
+ ],
+ ], $config);
}
public function testShouldSetNullTransportIfNullGiven()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
+
+ $rootNode->append(TransportFactory::getConfiguration());
- $transport->addTransportConfiguration($rootNode);
$processor = new Processor();
+ $config = $processor->process($tb->buildTree(), [['transport' => null]]);
- $config = $processor->process($tb->buildTree(), [null]);
- $this->assertEquals(['dsn' => 'null:'], $config);
+ $this->assertEquals([
+ 'transport' => [
+ 'dsn' => 'null:',
+ ],
+ ], $config);
}
public function testShouldSetNullTransportIfEmptyStringGiven()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
+
+ $rootNode->append(TransportFactory::getConfiguration());
- $transport->addTransportConfiguration($rootNode);
$processor = new Processor();
+ $config = $processor->process($tb->buildTree(), [['transport' => '']]);
- $config = $processor->process($tb->buildTree(), ['']);
- $this->assertEquals(['dsn' => 'null:'], $config);
+ $this->assertEquals([
+ 'transport' => [
+ 'dsn' => 'null:',
+ ],
+ ], $config);
}
public function testShouldSetNullTransportIfEmptyArrayGiven()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
+
+ $rootNode->append(TransportFactory::getConfiguration());
- $transport->addTransportConfiguration($rootNode);
$processor = new Processor();
+ $config = $processor->process($tb->buildTree(), [['transport' => []]]);
- $config = $processor->process($tb->buildTree(), [[]]);
- $this->assertEquals(['dsn' => 'null:'], $config);
+ $this->assertEquals([
+ 'transport' => [
+ 'dsn' => 'null:',
+ ],
+ ], $config);
}
public function testThrowIfEmptyDsnGiven()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
- $transport->addTransportConfiguration($rootNode);
- $processor = new Processor();
+ $rootNode->append(TransportFactory::getConfiguration());
+ $processor = new Processor();
$this->expectException(InvalidConfigurationException::class);
- $this->expectExceptionMessage('The path "foo.dsn" cannot contain an empty value, but got "".');
- $processor->process($tb->buildTree(), [['dsn' => '']]);
+ $this->expectExceptionMessage('The path "foo.transport.dsn" cannot contain an empty value, but got "".');
+ $processor->process($tb->buildTree(), [['transport' => ['dsn' => '']]]);
}
public function testThrowIfFactoryClassAndFactoryServiceSetAtTheSameTime()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
+
+ $rootNode->append(TransportFactory::getConfiguration());
- $transport->addTransportConfiguration($rootNode);
$processor = new Processor();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Both options factory_class and factory_service are set. Please choose one.');
$processor->process($tb->buildTree(), [[
- 'dsn' => 'foo:',
- 'factory_class' => 'aFactoryClass',
- 'factory_service' => 'aFactoryService',
- ]]);
+ 'transport' => [
+ 'dsn' => 'foo:',
+ 'factory_class' => 'aFactoryClass',
+ 'factory_service' => 'aFactoryService',
+ ], ]]);
}
public function testThrowIfConnectionFactoryClassUsedWithFactoryClassAtTheSameTime()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
+
+ $rootNode->append(TransportFactory::getConfiguration());
- $transport->addTransportConfiguration($rootNode);
$processor = new Processor();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The option connection_factory_class must not be used with factory_class or factory_service at the same time. Please choose one.');
$processor->process($tb->buildTree(), [[
- 'dsn' => 'foo:',
- 'connection_factory_class' => 'aFactoryClass',
- 'factory_service' => 'aFactoryService',
- ]]);
+ 'transport' => [
+ 'dsn' => 'foo:',
+ 'connection_factory_class' => 'aFactoryClass',
+ 'factory_service' => 'aFactoryService',
+ ], ]]);
}
public function testThrowIfConnectionFactoryClassUsedWithFactoryServiceAtTheSameTime()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
- $transport->addTransportConfiguration($rootNode);
+ $rootNode->append(TransportFactory::getConfiguration());
$processor = new Processor();
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The option connection_factory_class must not be used with factory_class or factory_service at the same time. Please choose one.');
$processor->process($tb->buildTree(), [[
- 'dsn' => 'foo:',
- 'connection_factory_class' => 'aFactoryClass',
- 'factory_service' => 'aFactoryService',
- ]]);
+ 'transport' => [
+ 'dsn' => 'foo:',
+ 'connection_factory_class' => 'aFactoryClass',
+ 'factory_service' => 'aFactoryService',
+ ], ]]);
}
public function testShouldAllowSetFactoryClass()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
- $transport->addTransportConfiguration($rootNode);
+ $rootNode->append(TransportFactory::getConfiguration());
$processor = new Processor();
$config = $processor->process($tb->buildTree(), [[
- 'dsn' => 'foo:',
- 'factory_class' => 'theFactoryClass',
- ]]);
+ 'transport' => [
+ 'dsn' => 'foo:',
+ 'factory_class' => 'theFactoryClass',
+ ], ]]);
- $this->assertArrayHasKey('factory_class', $config);
- $this->assertSame('theFactoryClass', $config['factory_class']);
+ $this->assertArrayHasKey('factory_class', $config['transport']);
+ $this->assertSame('theFactoryClass', $config['transport']['factory_class']);
}
public function testShouldAllowSetFactoryService()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
- $transport->addTransportConfiguration($rootNode);
+ $rootNode->append(TransportFactory::getConfiguration());
$processor = new Processor();
$config = $processor->process($tb->buildTree(), [[
- 'dsn' => 'foo:',
- 'factory_service' => 'theFactoryService',
- ]]);
+ 'transport' => [
+ 'dsn' => 'foo:',
+ 'factory_service' => 'theFactoryService',
+ ], ]]);
- $this->assertArrayHasKey('factory_service', $config);
- $this->assertSame('theFactoryService', $config['factory_service']);
+ $this->assertArrayHasKey('factory_service', $config['transport']);
+ $this->assertSame('theFactoryService', $config['transport']['factory_service']);
}
public function testShouldAllowSetConnectionFactoryClass()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
- $transport->addTransportConfiguration($rootNode);
+ $rootNode->append(TransportFactory::getConfiguration());
$processor = new Processor();
$config = $processor->process($tb->buildTree(), [[
- 'dsn' => 'foo:',
- 'connection_factory_class' => 'theFactoryClass',
- ]]);
+ 'transport' => [
+ 'dsn' => 'foo:',
+ 'connection_factory_class' => 'theFactoryClass',
+ ], ]]);
- $this->assertArrayHasKey('connection_factory_class', $config);
- $this->assertSame('theFactoryClass', $config['connection_factory_class']);
+ $this->assertArrayHasKey('connection_factory_class', $config['transport']);
+ $this->assertSame('theFactoryClass', $config['transport']['connection_factory_class']);
}
public function testThrowIfExtraOptionGiven()
{
- $transport = new TransportFactory('default');
- $tb = new TreeBuilder();
- $rootNode = $tb->root('foo');
+ list($tb, $rootNode) = $this->getRootNode();
- $transport->addTransportConfiguration($rootNode);
+ $rootNode->append(TransportFactory::getConfiguration());
$processor = new Processor();
- $config = $processor->process($tb->buildTree(), [['dsn' => 'foo:', 'extraOption' => 'aVal']]);
- $this->assertEquals(
- ['dsn' => 'foo:', 'extraOption' => 'aVal'],
- $config
+ $config = $processor->process($tb->buildTree(), [['transport' => ['dsn' => 'foo:', 'extraOption' => 'aVal']]]);
+ $this->assertEquals([
+ 'transport' => [
+ 'dsn' => 'foo:',
+ 'extraOption' => 'aVal',
+ ], ], $config
);
}
@@ -256,7 +259,14 @@ public function testShouldBuildConnectionFactoryFromDSN()
$transport = new TransportFactory('default');
- $transport->buildConnectionFactory($container, ['dsn' => 'foo://bar/baz']);
+ $config = [
+ 'dsn' => 'foo://bar/baz',
+ 'connection_factory_class' => null,
+ 'factory_service' => null,
+ 'factory_class' => null,
+ ];
+
+ $transport->buildConnectionFactory($container, $config);
$this->assertTrue($container->hasDefinition('enqueue.transport.default.connection_factory'));
@@ -449,4 +459,20 @@ public function testThrowIfBuildRpcClientCalledButContextServiceDoesNotExist()
$this->expectExceptionMessage('The service "enqueue.transport.default.context" does not exist.');
$transport->buildRpcClient($container, []);
}
+
+ /**
+ * @return [TreeBuilder, NodeDefinition]
+ */
+ private function getRootNode(): array
+ {
+ if (method_exists(TreeBuilder::class, 'getRootNode')) {
+ $tb = new TreeBuilder('foo');
+
+ return [$tb, $tb->getRootNode()];
+ }
+
+ $tb = new TreeBuilder();
+
+ return [$tb, $tb->root('foo')];
+ }
}
diff --git a/pkg/enqueue/Tests/Symfony/LazyProducerTest.php b/pkg/enqueue/Tests/Symfony/LazyProducerTest.php
new file mode 100644
index 000000000..c8ba596a8
--- /dev/null
+++ b/pkg/enqueue/Tests/Symfony/LazyProducerTest.php
@@ -0,0 +1,128 @@
+assertClassImplements(ProducerInterface::class, LazyProducer::class);
+ }
+
+ public function testShouldNotCallRealProducerInConstructor()
+ {
+ $containerMock = $this->createContainerMock();
+ $containerMock
+ ->expects($this->never())
+ ->method('get')
+ ;
+
+ new LazyProducer($containerMock, 'realProducerId');
+ }
+
+ public function testShouldProxyAllArgumentOnSendEvent()
+ {
+ $topic = 'theTopic';
+ $message = 'theMessage';
+
+ $realProducerMock = $this->createProducerMock();
+ $realProducerMock
+ ->expects($this->once())
+ ->method('sendEvent')
+ ->with($topic, $message)
+ ;
+
+ $containerMock = $this->createContainerMock();
+ $containerMock
+ ->expects($this->once())
+ ->method('get')
+ ->with('realProducerId')
+ ->willReturn($realProducerMock)
+ ;
+
+ $lazyProducer = new LazyProducer($containerMock, 'realProducerId');
+
+ $lazyProducer->sendEvent($topic, $message);
+ }
+
+ public function testShouldProxyAllArgumentOnSendCommand()
+ {
+ $command = 'theCommand';
+ $message = 'theMessage';
+ $needReply = false;
+
+ $realProducerMock = $this->createProducerMock();
+ $realProducerMock
+ ->expects($this->once())
+ ->method('sendCommand')
+ ->with($command, $message, $needReply)
+ ;
+
+ $containerMock = $this->createContainerMock();
+ $containerMock
+ ->expects($this->once())
+ ->method('get')
+ ->with('realProducerId')
+ ->willReturn($realProducerMock)
+ ;
+
+ $lazyProducer = new LazyProducer($containerMock, 'realProducerId');
+
+ $result = $lazyProducer->sendCommand($command, $message, $needReply);
+
+ $this->assertNull($result);
+ }
+
+ public function testShouldProxyReturnedPromiseBackOnSendCommand()
+ {
+ $expectedPromise = $this->createMock(Promise::class);
+
+ $realProducerMock = $this->createProducerMock();
+ $realProducerMock
+ ->expects($this->once())
+ ->method('sendCommand')
+ ->willReturn($expectedPromise)
+ ;
+
+ $containerMock = $this->createContainerMock();
+ $containerMock
+ ->expects($this->once())
+ ->method('get')
+ ->with('realProducerId')
+ ->willReturn($realProducerMock)
+ ;
+
+ $lazyProducer = new LazyProducer($containerMock, 'realProducerId');
+
+ $actualPromise = $lazyProducer->sendCommand('aCommand', 'aMessage', true);
+
+ $this->assertSame($expectedPromise, $actualPromise);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|ProducerInterface
+ */
+ private function createProducerMock(): ProducerInterface
+ {
+ return $this->createMock(ProducerInterface::class);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|ContainerInterface
+ */
+ private function createContainerMock(): ContainerInterface
+ {
+ return $this->createMock(ContainerInterface::class);
+ }
+}
diff --git a/pkg/enqueue/Tests/Util/Fixtures/JsonSerializableClass.php b/pkg/enqueue/Tests/Util/Fixtures/JsonSerializableClass.php
index b612978e7..1a77ce0cf 100644
--- a/pkg/enqueue/Tests/Util/Fixtures/JsonSerializableClass.php
+++ b/pkg/enqueue/Tests/Util/Fixtures/JsonSerializableClass.php
@@ -6,7 +6,8 @@ class JsonSerializableClass implements \JsonSerializable
{
public $keyPublic = 'public';
- public function jsonSerialize()
+ #[\ReturnTypeWillChange]
+ public function jsonSerialize(): array
{
return [
'key' => 'value',
diff --git a/pkg/enqueue/Tests/Util/JSONTest.php b/pkg/enqueue/Tests/Util/JSONTest.php
index c37862eb0..1a3df4211 100644
--- a/pkg/enqueue/Tests/Util/JSONTest.php
+++ b/pkg/enqueue/Tests/Util/JSONTest.php
@@ -16,7 +16,8 @@ public function testShouldDecodeString()
public function testThrowIfMalformedJson()
{
- $this->setExpectedException(\InvalidArgumentException::class, 'The malformed json given. ');
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('The malformed json given. ');
$this->assertSame(['foo' => 'fooVal'], JSON::decode('{]'));
}
@@ -38,15 +39,11 @@ public function nonStringDataProvider()
/**
* @dataProvider nonStringDataProvider
- *
- * @param mixed $value
*/
public function testShouldThrowExceptionIfInputIsNotString($value)
{
- $this->setExpectedException(
- \InvalidArgumentException::class,
- 'Accept only string argument but got:'
- );
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Accept only string argument but got:');
$this->assertSame(0, JSON::decode($value));
}
@@ -96,10 +93,8 @@ public function testShouldEncodeObjectOfJsonSerializableClass()
public function testThrowIfValueIsResource()
{
- $this->setExpectedException(
- \InvalidArgumentException::class,
- 'Could not encode value into json. Error 8 and message Type is not supported'
- );
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Could not encode value into json. Error 8 and message Type is not supported');
$resource = fopen('php://memory', 'r');
fclose($resource);
diff --git a/pkg/enqueue/Tests/Util/UUIDTest.php b/pkg/enqueue/Tests/Util/UUIDTest.php
index ac3090315..f21693e78 100644
--- a/pkg/enqueue/Tests/Util/UUIDTest.php
+++ b/pkg/enqueue/Tests/Util/UUIDTest.php
@@ -11,7 +11,7 @@ public function testShouldGenerateUniqueId()
{
$uuid = UUID::generate();
- $this->assertInternalType('string', $uuid);
+ $this->assertIsString($uuid);
$this->assertEquals(36, strlen($uuid));
}
diff --git a/pkg/enqueue/Tests/Util/VarExportTest.php b/pkg/enqueue/Tests/Util/VarExportTest.php
index 1d2384ac9..b71e78a65 100644
--- a/pkg/enqueue/Tests/Util/VarExportTest.php
+++ b/pkg/enqueue/Tests/Util/VarExportTest.php
@@ -7,16 +7,8 @@
class VarExportTest extends TestCase
{
- public function testCouldBeConstructedWithValueAsArgument()
- {
- new VarExport('aVal');
- }
-
/**
* @dataProvider provideValues
- *
- * @param mixed $value
- * @param mixed $expected
*/
public function testShouldConvertValueToStringUsingVarExportFunction($value, $expected)
{
diff --git a/pkg/enqueue/Tests/fix_composer_json.php b/pkg/enqueue/Tests/fix_composer_json.php
index bce1ebb75..324f1840b 100644
--- a/pkg/enqueue/Tests/fix_composer_json.php
+++ b/pkg/enqueue/Tests/fix_composer_json.php
@@ -4,8 +4,8 @@
$composerJson = json_decode(file_get_contents(__DIR__.'/../composer.json'), true);
-$composerJson['config']['platform']['ext-amqp'] = '1.7';
+$composerJson['config']['platform']['ext-amqp'] = '1.9.3';
$composerJson['config']['platform']['ext-rdkafka'] = '3.3';
-$composerJson['config']['platform']['ext-gearman'] = '1.1';
+$composerJson['config']['platform']['ext-gearman'] = '2';
-file_put_contents(__DIR__.'/../composer.json', json_encode($composerJson, JSON_PRETTY_PRINT));
+file_put_contents(__DIR__.'/../composer.json', json_encode($composerJson, \JSON_PRETTY_PRINT));
diff --git a/pkg/enqueue/Util/JSON.php b/pkg/enqueue/Util/JSON.php
index f85738e1d..67411af16 100644
--- a/pkg/enqueue/Util/JSON.php
+++ b/pkg/enqueue/Util/JSON.php
@@ -14,10 +14,7 @@ class JSON
public static function decode($string)
{
if (!is_string($string)) {
- throw new \InvalidArgumentException(sprintf(
- 'Accept only string argument but got: "%s"',
- is_object($string) ? get_class($string) : gettype($string)
- ));
+ throw new \InvalidArgumentException(sprintf('Accept only string argument but got: "%s"', is_object($string) ? $string::class : gettype($string)));
}
// PHP7 fix - empty string and null cause syntax error
@@ -26,32 +23,22 @@ public static function decode($string)
}
$decoded = json_decode($string, true);
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'The malformed json given. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
}
return $decoded;
}
/**
- * @param mixed $value
- *
* @return string
*/
public static function encode($value)
{
- $encoded = json_encode($value, JSON_UNESCAPED_UNICODE);
-
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'Could not encode value into json. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ $encoded = json_encode($value, \JSON_UNESCAPED_UNICODE);
+
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('Could not encode value into json. Error %s and message %s', json_last_error(), json_last_error_msg()));
}
return $encoded;
diff --git a/pkg/enqueue/Util/Stringify.php b/pkg/enqueue/Util/Stringify.php
index 39b1f1305..d8a48a8d6 100644
--- a/pkg/enqueue/Util/Stringify.php
+++ b/pkg/enqueue/Util/Stringify.php
@@ -7,14 +7,8 @@
*/
class Stringify
{
- /**
- * @var mixed
- */
private $value;
- /**
- * @param mixed $value
- */
public function __construct($value)
{
$this->value = $value;
@@ -26,11 +20,11 @@ public function __toString(): string
return $this->value;
}
- return json_encode($this->value, JSON_UNESCAPED_SLASHES);
+ return json_encode($this->value, \JSON_UNESCAPED_SLASHES);
}
public static function that($value): self
{
- return new static($value);
+ return new self($value);
}
}
diff --git a/pkg/enqueue/Util/VarExport.php b/pkg/enqueue/Util/VarExport.php
index 4a48afadd..9a914706d 100644
--- a/pkg/enqueue/Util/VarExport.php
+++ b/pkg/enqueue/Util/VarExport.php
@@ -7,14 +7,8 @@
*/
class VarExport
{
- /**
- * @var mixed
- */
private $value;
- /**
- * @param mixed $value
- */
public function __construct($value)
{
$this->value = $value;
diff --git a/pkg/enqueue/composer.json b/pkg/enqueue/composer.json
index e42f5e9f6..db85e0bcb 100644
--- a/pkg/enqueue/composer.json
+++ b/pkg/enqueue/composer.json
@@ -6,43 +6,45 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "queue-interop/amqp-interop": "0.8.x-dev",
- "queue-interop/queue-interop": "0.7.x-dev",
- "enqueue/null": "0.9.x-dev",
- "ramsey/uuid": "^2|^3.5",
- "psr/log": "^1",
- "psr/container": "^1"
+ "php": "^8.1",
+ "queue-interop/amqp-interop": "^0.8.2",
+ "queue-interop/queue-interop": "^0.8",
+ "enqueue/null": "^0.10",
+ "enqueue/dsn": "^0.10",
+ "ramsey/uuid": "^3.5|^4",
+ "psr/log": "^1.0 || ^2.0 || ^3.0",
+ "psr/container": "^1.1 || ^2.0"
},
"require-dev": {
- "phpunit/phpunit": "~5.5",
- "symfony/console": "^3.4|^4",
- "symfony/dependency-injection": "^3.4|^4",
- "symfony/config": "^3.4|^4",
- "symfony/event-dispatcher": "^3.4|^4",
- "symfony/http-kernel": "^3.4|^4",
- "enqueue/amqp-ext": "0.9.x-dev",
- "enqueue/amqp-lib": "0.9.x-dev",
- "enqueue/amqp-bunny": "0.9.x-dev",
- "enqueue/pheanstalk": "0.9.x-dev",
- "enqueue/gearman": "0.9.x-dev",
- "enqueue/rdkafka": "0.9.x-dev",
- "enqueue/dbal": "0.9.x-dev",
- "enqueue/fs": "0.9.x-dev",
- "enqueue/gps": "0.9.x-dev",
- "enqueue/redis": "0.9.x-dev",
- "enqueue/sqs": "0.9.x-dev",
- "enqueue/stomp": "0.9.x-dev",
- "enqueue/test": "0.9.x-dev",
- "enqueue/simple-client": "0.9.x-dev",
- "enqueue/mongodb": "0.9.x-dev",
+ "phpunit/phpunit": "^9.5",
+ "symfony/console": "^7.0|^8.0",
+ "symfony/dependency-injection": "^7.0|^8.0",
+ "symfony/config": "^7.0|^8.0",
+ "symfony/event-dispatcher": "^7.0|^8.0",
+ "symfony/http-kernel": "^7.0|^8.0",
+ "symfony/yaml": "^7.0|^8.0",
+ "enqueue/amqp-ext": "0.10.x-dev",
+ "enqueue/amqp-lib": "0.10.x-dev",
+ "enqueue/amqp-bunny": "0.10.x-dev",
+ "enqueue/pheanstalk": "0.10.x-dev",
+ "enqueue/gearman": "0.10.x-dev",
+ "enqueue/rdkafka": "0.10.x-dev",
+ "enqueue/dbal": "0.10.x-dev",
+ "enqueue/fs": "0.10.x-dev",
+ "enqueue/gps": "0.10.x-dev",
+ "enqueue/redis": "0.10.x-dev",
+ "enqueue/sqs": "0.10.x-dev",
+ "enqueue/stomp": "0.10.x-dev",
+ "enqueue/test": "0.10.x-dev",
+ "enqueue/simple-client": "0.10.x-dev",
+ "enqueue/mongodb": "0.10.x-dev",
"empi89/php-amqp-stubs": "*@dev",
- "enqueue/dsn": "0.9.x-dev"
+ "enqueue/dsn": "0.10.x-dev"
},
"suggest": {
- "symfony/console": "^2.8|^3|^4 If you want to use li commands",
- "symfony/dependency-injection": "^3.4|^4",
- "symfony/config": "^3.4|^4",
+ "symfony/console": "^7.0|^8.0 If you want to use cli commands",
+ "symfony/dependency-injection": "^7.0|^8.0",
+ "symfony/config": "^7.0|^8.0",
"enqueue/amqp-ext": "AMQP transport (based on php extension)",
"enqueue/stomp": "STOMP transport",
"enqueue/fs": "Filesystem transport",
@@ -71,7 +73,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/enqueue/phpunit.xml.dist b/pkg/enqueue/phpunit.xml.dist
index 156ab4929..69c12ca1e 100644
--- a/pkg/enqueue/phpunit.xml.dist
+++ b/pkg/enqueue/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/fs/.gitattributes b/pkg/fs/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/fs/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/fs/.github/workflows/ci.yml b/pkg/fs/.github/workflows/ci.yml
new file mode 100644
index 000000000..bbfcd19d5
--- /dev/null
+++ b/pkg/fs/.github/workflows/ci.yml
@@ -0,0 +1,29 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: SYMFONY_DEPRECATIONS_HELPER=weak vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/fs/.travis.yml b/pkg/fs/.travis.yml
deleted file mode 100644
index 2c39f47da..000000000
--- a/pkg/fs/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-sudo: false
-
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
- - '7.2'
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - composer self-update
- - composer install --prefer-source
-
-script:
- - SYMFONY_DEPRECATIONS_HELPER=weak vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/fs/FsConnectionFactory.php b/pkg/fs/FsConnectionFactory.php
index c35c52e5a..9c4ba17e5 100644
--- a/pkg/fs/FsConnectionFactory.php
+++ b/pkg/fs/FsConnectionFactory.php
@@ -4,6 +4,7 @@
namespace Enqueue\Fs;
+use Enqueue\Dsn\Dsn;
use Interop\Queue\ConnectionFactory;
use Interop\Queue\Context;
@@ -27,23 +28,31 @@ class FsConnectionFactory implements ConnectionFactory
* or
*
* file: - create queue files in tmp dir.
- * file://home/foo/enqueue
- * file://home/foo/enqueue?pre_fetch_count=20&chmod=0777
+ * file:///home/foo/enqueue
+ * file:///home/foo/enqueue?pre_fetch_count=20&chmod=0777
*
* @param array|string|null $config
*/
public function __construct($config = 'file:')
{
if (empty($config) || 'file:' === $config) {
- $config = ['path' => sys_get_temp_dir().'/enqueue'];
+ $config = $this->parseDsn('file://'.sys_get_temp_dir().'/enqueue');
} elseif (is_string($config)) {
- $config = $this->parseDsn($config);
+ if ('/' === $config[0]) {
+ $config = $this->parseDsn('file://'.$config);
+ } else {
+ $config = $this->parseDsn($config);
+ }
} elseif (is_array($config)) {
} else {
throw new \LogicException('The config must be either an array of options, a DSN string or null');
}
$this->config = array_replace($this->defaultConfig(), $config);
+
+ if (empty($this->config['path'])) {
+ throw new \LogicException('The path option must be set.');
+ }
}
/**
@@ -61,39 +70,19 @@ public function createContext(): Context
private function parseDsn(string $dsn): array
{
- if ($dsn && '/' === $dsn[0]) {
- return ['path' => $dsn];
- }
-
- if (false === strpos($dsn, 'file:')) {
- throw new \LogicException(sprintf('The given DSN "%s" is not supported. Must start with "file:".', $dsn));
- }
-
- $dsn = substr($dsn, 7);
-
- $path = parse_url($dsn, PHP_URL_PATH);
- $query = parse_url($dsn, PHP_URL_QUERY);
+ $dsn = Dsn::parseFirst($dsn);
- if ('/' != $path[0]) {
- throw new \LogicException(sprintf('Failed to parse DSN path "%s". The path must start with "/"', $path));
+ $supportedSchemes = ['file'];
+ if (false == in_array($dsn->getSchemeProtocol(), $supportedSchemes, true)) {
+ throw new \LogicException(sprintf('The given scheme protocol "%s" is not supported. It must be one of "%s"', $dsn->getSchemeProtocol(), implode('", "', $supportedSchemes)));
}
- if ($query) {
- $config = [];
- parse_str($query, $config);
- }
-
- if (isset($config['pre_fetch_count'])) {
- $config['pre_fetch_count'] = (int) $config['pre_fetch_count'];
- }
-
- if (isset($config['chmod'])) {
- $config['chmod'] = intval($config['chmod'], 8);
- }
-
- $config['path'] = $path;
-
- return $config;
+ return array_filter(array_replace($dsn->getQuery(), [
+ 'path' => $dsn->getPath(),
+ 'pre_fetch_count' => $dsn->getDecimal('pre_fetch_count'),
+ 'chmod' => $dsn->getOctal('chmod'),
+ 'polling_interval' => $dsn->getDecimal('polling_interval'),
+ ]), function ($value) { return null !== $value; });
}
private function defaultConfig(): array
diff --git a/pkg/fs/FsConsumer.php b/pkg/fs/FsConsumer.php
index d9092aaf4..614461eb2 100644
--- a/pkg/fs/FsConsumer.php
+++ b/pkg/fs/FsConsumer.php
@@ -90,7 +90,7 @@ public function receive(int $timeout = 0): ?Message
return null;
}
- usleep($this->pollingInterval);
+ usleep($this->pollingInterval * 1000);
if ($timeout && (microtime(true) - $startAt) >= $timeout) {
return null;
@@ -112,7 +112,7 @@ public function receiveNoWait(): ?Message
while ($count) {
$frame = $this->readFrame($file, 1);
- //guards
+ // guards
if ($frame && false == ('|' == $frame[0] || ' ' == $frame[0])) {
throw new \LogicException(sprintf('The frame could start from either " " or "|". The malformed frame starts with "%s".', $frame[0]));
}
@@ -137,7 +137,7 @@ public function receiveNoWait(): ?Message
$this->preFetchedMessages[] = $fetchedMessage;
} catch (\Exception $e) {
- throw new \LogicException(sprintf("Cannot decode json message '%s'", $rawMessage), null, $e);
+ throw new \LogicException(sprintf("Cannot decode json message '%s'", $rawMessage), 0, $e);
}
} else {
return null;
@@ -188,13 +188,13 @@ private function readFrame($file, int $frameNumber): string
$frameSize = 64;
$offset = $frameNumber * $frameSize;
- fseek($file, -$offset, SEEK_END);
+ fseek($file, -$offset, \SEEK_END);
$frame = fread($file, $frameSize);
if ('' == $frame) {
return '';
}
- if (false !== strpos($frame, '|{')) {
+ if (str_contains($frame, '|{')) {
return $frame;
}
diff --git a/pkg/fs/FsContext.php b/pkg/fs/FsContext.php
index 0d499526c..c735e13aa 100644
--- a/pkg/fs/FsContext.php
+++ b/pkg/fs/FsContext.php
@@ -83,7 +83,7 @@ public function createQueue(string $queueName): Queue
public function declareDestination(FsDestination $destination): void
{
- //InvalidDestinationException::assertDestinationInstanceOf($destination, FsDestination::class);
+ // InvalidDestinationException::assertDestinationInstanceOf($destination, FsDestination::class);
set_error_handler(function ($severity, $message, $file, $line) {
throw new \ErrorException($message, 0, $severity, $file, $line);
@@ -105,7 +105,7 @@ public function workWithFile(FsDestination $destination, string $mode, callable
set_error_handler(function ($severity, $message, $file, $line) {
throw new \ErrorException($message, 0, $severity, $file, $line);
- });
+ }, \E_ALL & ~\E_USER_DEPRECATED);
try {
$file = fopen((string) $destination->getFileInfo(), $mode);
diff --git a/pkg/fs/FsMessage.php b/pkg/fs/FsMessage.php
index d66ee52cd..45312e52c 100644
--- a/pkg/fs/FsMessage.php
+++ b/pkg/fs/FsMessage.php
@@ -96,7 +96,7 @@ public function setRedelivered(bool $redelivered): void
$this->redelivered = $redelivered;
}
- public function setCorrelationId(string $correlationId = null): void
+ public function setCorrelationId(?string $correlationId = null): void
{
$this->setHeader('correlation_id', (string) $correlationId);
}
@@ -106,7 +106,7 @@ public function getCorrelationId(): ?string
return $this->getHeader('correlation_id');
}
- public function setMessageId(string $messageId = null): void
+ public function setMessageId(?string $messageId = null): void
{
$this->setHeader('message_id', (string) $messageId);
}
@@ -123,12 +123,12 @@ public function getTimestamp(): ?int
return null === $value ? null : (int) $value;
}
- public function setTimestamp(int $timestamp = null): void
+ public function setTimestamp(?int $timestamp = null): void
{
$this->setHeader('timestamp', $timestamp);
}
- public function setReplyTo(string $replyTo = null): void
+ public function setReplyTo(?string $replyTo = null): void
{
$this->setHeader('reply_to', $replyTo);
}
@@ -150,12 +150,8 @@ public function jsonSerialize(): array
public static function jsonUnserialize(string $json): self
{
$data = json_decode($json, true);
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'The malformed json given. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
}
return new self($data['body'], $data['properties'], $data['headers']);
diff --git a/pkg/fs/FsProducer.php b/pkg/fs/FsProducer.php
index 55ff88cc3..067e54b36 100644
--- a/pkg/fs/FsProducer.php
+++ b/pkg/fs/FsProducer.php
@@ -53,12 +53,8 @@ public function send(Destination $destination, Message $message): void
$rawMessage = str_replace('|{', '\|\{', $rawMessage);
$rawMessage = '|'.$rawMessage;
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'Could not encode value into json. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('Could not encode value into json. Error %s and message %s', json_last_error(), json_last_error_msg()));
}
$rawMessage = str_repeat(' ', 64 - (strlen($rawMessage) % 64)).$rawMessage;
@@ -67,7 +63,7 @@ public function send(Destination $destination, Message $message): void
});
}
- public function setDeliveryDelay(int $deliveryDelay = null): Producer
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
{
if (null === $deliveryDelay) {
return $this;
@@ -81,7 +77,7 @@ public function getDeliveryDelay(): ?int
return null;
}
- public function setPriority(int $priority = null): Producer
+ public function setPriority(?int $priority = null): Producer
{
if (null === $priority) {
return $this;
@@ -95,7 +91,7 @@ public function getPriority(): ?int
return null;
}
- public function setTimeToLive(int $timeToLive = null): Producer
+ public function setTimeToLive(?int $timeToLive = null): Producer
{
$this->timeToLive = $timeToLive;
diff --git a/pkg/fs/LegacyFilesystemLock.php b/pkg/fs/LegacyFilesystemLock.php
index a765d2ced..328fb7098 100644
--- a/pkg/fs/LegacyFilesystemLock.php
+++ b/pkg/fs/LegacyFilesystemLock.php
@@ -19,9 +19,6 @@ public function __construct()
$this->lockHandlers = [];
}
- /**
- * {@inheritdoc}
- */
public function lock(FsDestination $destination)
{
$lockHandler = $this->getLockHandler($destination);
@@ -31,9 +28,6 @@ public function lock(FsDestination $destination)
}
}
- /**
- * {@inheritdoc}
- */
public function release(FsDestination $destination)
{
$lockHandler = $this->getLockHandler($destination);
@@ -51,8 +45,6 @@ public function releaseAll()
}
/**
- * @param FsDestination $destination
- *
* @return LockHandler
*/
private function getLockHandler(FsDestination $destination)
@@ -161,7 +153,7 @@ public function lock($blocking = false)
// On Windows, even if PHP doc says the contrary, LOCK_NB works, see
// https://bugs.php.net/54129
- if (!flock($this->handle, LOCK_EX | ($blocking ? 0 : LOCK_NB))) {
+ if (!flock($this->handle, \LOCK_EX | ($blocking ? 0 : \LOCK_NB))) {
fclose($this->handle);
$this->handle = null;
@@ -177,7 +169,7 @@ public function lock($blocking = false)
public function release()
{
if ($this->handle) {
- flock($this->handle, LOCK_UN | LOCK_NB);
+ flock($this->handle, \LOCK_UN | \LOCK_NB);
fclose($this->handle);
$this->handle = null;
}
diff --git a/pkg/fs/Lock.php b/pkg/fs/Lock.php
index 91125faa8..16349f22c 100644
--- a/pkg/fs/Lock.php
+++ b/pkg/fs/Lock.php
@@ -10,15 +10,10 @@ interface Lock
* Returns the control If the look has been obtained
* If not, should throw CannotObtainLockException exception.
*
- * @param FsDestination $destination
- *
* @throws CannotObtainLockException if look could not be obtained
*/
public function lock(FsDestination $destination);
- /**
- * @param FsDestination $destination
- */
public function release(FsDestination $destination);
public function releaseAll();
diff --git a/pkg/fs/README.md b/pkg/fs/README.md
index 7822f354c..4b4b502dc 100644
--- a/pkg/fs/README.md
+++ b/pkg/fs/README.md
@@ -1,26 +1,39 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Enqueue Filesystem Transport
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/fs)
+[](https://github.com/php-enqueue/fs/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/fs)
[](https://packagist.org/packages/enqueue/fs)
-
+
This is an implementation of Queue Interop specification. It allows you to send and consume message stored locally in files.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/transport/filesystem/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
diff --git a/pkg/fs/Tests/FsConnectionFactoryConfigTest.php b/pkg/fs/Tests/FsConnectionFactoryConfigTest.php
index c79581c51..0b3411f2c 100644
--- a/pkg/fs/Tests/FsConnectionFactoryConfigTest.php
+++ b/pkg/fs/Tests/FsConnectionFactoryConfigTest.php
@@ -4,6 +4,7 @@
use Enqueue\Fs\FsConnectionFactory;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use PHPUnit\Framework\TestCase;
/**
@@ -12,6 +13,7 @@
class FsConnectionFactoryConfigTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testThrowNeitherArrayStringNorNullGivenAsConfig()
{
@@ -21,10 +23,10 @@ public function testThrowNeitherArrayStringNorNullGivenAsConfig()
new FsConnectionFactory(new \stdClass());
}
- public function testThrowIfSchemeIsNotAmqp()
+ public function testThrowIfSchemeIsNotFileScheme()
{
$this->expectException(\LogicException::class);
- $this->expectExceptionMessage('The given DSN "http://example.com" is not supported. Must start with "file:');
+ $this->expectExceptionMessage('The given scheme protocol "http" is not supported. It must be one of "file"');
new FsConnectionFactory('http://example.com');
}
@@ -32,16 +34,23 @@ public function testThrowIfSchemeIsNotAmqp()
public function testThrowIfDsnCouldNotBeParsed()
{
$this->expectException(\LogicException::class);
- $this->expectExceptionMessage('Failed to parse DSN path ":@/". The path must start with "/"');
+ $this->expectExceptionMessage('The DSN is invalid.');
- new FsConnectionFactory('file://:@/');
+ new FsConnectionFactory('foo');
+ }
+
+ public function testThrowIfArrayConfigGivenWithEmptyPath()
+ {
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The path option must be set.');
+
+ new FsConnectionFactory([
+ 'path' => null,
+ ]);
}
/**
* @dataProvider provideConfigs
- *
- * @param mixed $config
- * @param mixed $expectedConfig
*/
public function testShouldParseConfigurationAsExpected($config, $expectedConfig)
{
diff --git a/pkg/fs/Tests/FsConnectionFactoryTest.php b/pkg/fs/Tests/FsConnectionFactoryTest.php
index 35558573a..2df442342 100644
--- a/pkg/fs/Tests/FsConnectionFactoryTest.php
+++ b/pkg/fs/Tests/FsConnectionFactoryTest.php
@@ -5,11 +5,13 @@
use Enqueue\Fs\FsConnectionFactory;
use Enqueue\Fs\FsContext;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use Interop\Queue\ConnectionFactory;
class FsConnectionFactoryTest extends \PHPUnit\Framework\TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testShouldImplementConnectionFactoryInterface()
{
diff --git a/pkg/fs/Tests/FsConsumerTest.php b/pkg/fs/Tests/FsConsumerTest.php
index 90048b2d0..67f03ae98 100644
--- a/pkg/fs/Tests/FsConsumerTest.php
+++ b/pkg/fs/Tests/FsConsumerTest.php
@@ -20,11 +20,6 @@ public function testShouldImplementConsumerInterface()
$this->assertClassImplements(Consumer::class, FsConsumer::class);
}
- public function testCouldBeConstructedWithContextAndDestinationAndPreFetchCountAsArguments()
- {
- new FsConsumer($this->createContextMock(), new FsDestination(TempFile::generate()), 1);
- }
-
public function testShouldReturnDestinationSetInConstructorOnGetQueue()
{
$destination = new FsDestination(TempFile::generate());
@@ -50,6 +45,9 @@ public function testShouldAllowGetPreviouslySetPreFetchCount()
$this->assertSame(456, $consumer->getPreFetchCount());
}
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldDoNothingOnAcknowledge()
{
$consumer = new FsConsumer($this->createContextMock(), new FsDestination(TempFile::generate()), 123);
@@ -57,6 +55,9 @@ public function testShouldDoNothingOnAcknowledge()
$consumer->acknowledge(new FsMessage());
}
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldDoNothingOnReject()
{
$consumer = new FsConsumer($this->createContextMock(), new FsDestination(TempFile::generate()), 123);
@@ -134,7 +135,7 @@ public function testShouldWaitTwoSecondsForMessageAndExitOnReceive()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|FsProducer
+ * @return \PHPUnit\Framework\MockObject\MockObject|FsProducer
*/
private function createProducerMock()
{
@@ -142,7 +143,7 @@ private function createProducerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|FsContext
+ * @return \PHPUnit\Framework\MockObject\MockObject|FsContext
*/
private function createContextMock()
{
diff --git a/pkg/fs/Tests/FsContextTest.php b/pkg/fs/Tests/FsContextTest.php
index 377ec0007..9d5a5f1fc 100644
--- a/pkg/fs/Tests/FsContextTest.php
+++ b/pkg/fs/Tests/FsContextTest.php
@@ -9,6 +9,7 @@
use Enqueue\Fs\FsProducer;
use Enqueue\Null\NullQueue;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use Interop\Queue\Context;
use Interop\Queue\Exception\InvalidDestinationException;
use Makasim\File\TempFile;
@@ -16,17 +17,13 @@
class FsContextTest extends \PHPUnit\Framework\TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testShouldImplementContextInterface()
{
$this->assertClassImplements(Context::class, FsContext::class);
}
- public function testCouldBeConstructedWithExpectedArguments()
- {
- new FsContext(sys_get_temp_dir(), 1, 0666, 100);
- }
-
public function testShouldAllowCreateEmptyMessage()
{
$context = new FsContext(sys_get_temp_dir(), 1, 0666, 100);
@@ -120,6 +117,9 @@ public function testShouldThrowIfNotFsDestinationGivenOnCreateConsumer()
$this->assertInstanceOf(FsConsumer::class, $consumer);
}
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldCreateConsumer()
{
$tmpFile = new TempFile(sys_get_temp_dir().'/foo');
@@ -190,7 +190,7 @@ public function testShouldCreateFileOnFilesystemIfNotExistOnDeclareDestination()
$queue = $context->createQueue($tmpFile->getFilename());
- $this->assertFileNotExists((string) $tmpFile);
+ $this->assertFileDoesNotExist((string) $tmpFile);
$context->declareDestination($queue);
diff --git a/pkg/fs/Tests/FsMessageTest.php b/pkg/fs/Tests/FsMessageTest.php
index c2f788d04..90655b620 100644
--- a/pkg/fs/Tests/FsMessageTest.php
+++ b/pkg/fs/Tests/FsMessageTest.php
@@ -89,7 +89,7 @@ public function testCouldBeUnserializedFromJson()
$json = json_encode($message);
- //guard
+ // guard
$this->assertNotEmpty($json);
$unserializedMessage = FsMessage::jsonUnserialize($json);
diff --git a/pkg/fs/Tests/FsProducerTest.php b/pkg/fs/Tests/FsProducerTest.php
index 3311287a5..266854c7b 100644
--- a/pkg/fs/Tests/FsProducerTest.php
+++ b/pkg/fs/Tests/FsProducerTest.php
@@ -23,11 +23,6 @@ public function testShouldImplementProducerInterface()
$this->assertClassImplements(Producer::class, FsProducer::class);
}
- public function testCouldBeConstructedWithContextAsFirstArgument()
- {
- new FsProducer($this->createContextMock());
- }
-
public function testThrowIfDestinationNotFsOnSend()
{
$producer = new FsProducer($this->createContextMock());
@@ -63,7 +58,7 @@ public function testShouldCallContextWorkWithFileAndCallbackToItOnSend()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|FsContext
+ * @return \PHPUnit\Framework\MockObject\MockObject|FsContext
*/
private function createContextMock()
{
diff --git a/pkg/fs/Tests/Functional/FsCommonUseCasesTest.php b/pkg/fs/Tests/Functional/FsCommonUseCasesTest.php
index 6ad6f5569..b96091e7f 100644
--- a/pkg/fs/Tests/Functional/FsCommonUseCasesTest.php
+++ b/pkg/fs/Tests/Functional/FsCommonUseCasesTest.php
@@ -17,14 +17,14 @@ class FsCommonUseCasesTest extends \PHPUnit\Framework\TestCase
*/
private $fsContext;
- public function setUp()
+ protected function setUp(): void
{
$this->fsContext = (new FsConnectionFactory(['path' => sys_get_temp_dir()]))->createContext();
new TempFile(sys_get_temp_dir().'/fs_test_queue');
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->fsContext->close();
}
@@ -111,7 +111,7 @@ public function testConsumerReceiveMessageWithZeroTimeout()
$topic = $this->fsContext->createTopic('fs_test_queue_exchange');
$consumer = $this->fsContext->createConsumer($topic);
- //guard
+ // guard
$this->assertNull($consumer->receive(1000));
$message = $this->fsContext->createMessage(__METHOD__);
diff --git a/pkg/fs/Tests/Functional/FsConsumerTest.php b/pkg/fs/Tests/Functional/FsConsumerTest.php
index 50cab8533..3be009b02 100644
--- a/pkg/fs/Tests/Functional/FsConsumerTest.php
+++ b/pkg/fs/Tests/Functional/FsConsumerTest.php
@@ -15,14 +15,14 @@ class FsConsumerTest extends TestCase
*/
private $fsContext;
- public function setUp()
+ protected function setUp(): void
{
$this->fsContext = (new FsConnectionFactory(['path' => sys_get_temp_dir()]))->createContext();
$this->fsContext->purgeQueue($this->fsContext->createQueue('fs_test_queue'));
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->fsContext->close();
}
@@ -159,7 +159,7 @@ public function testShouldThrowExceptionWhenFrameSizeNotDivideExactly()
$context->workWithFile($queue, 'a+', function (FsDestination $destination, $file) {
$msg = '|{"body":""}';
- //guard
+ // guard
$this->assertNotSame(0, strlen($msg) % 64);
fwrite($file, $msg);
diff --git a/pkg/fs/Tests/Functional/FsConsumptionUseCasesTest.php b/pkg/fs/Tests/Functional/FsConsumptionUseCasesTest.php
index 7ea11c74c..334a8fe7d 100644
--- a/pkg/fs/Tests/Functional/FsConsumptionUseCasesTest.php
+++ b/pkg/fs/Tests/Functional/FsConsumptionUseCasesTest.php
@@ -25,14 +25,14 @@ class FsConsumptionUseCasesTest extends \PHPUnit\Framework\TestCase
*/
private $fsContext;
- public function setUp()
+ protected function setUp(): void
{
$this->fsContext = (new FsConnectionFactory(['path' => sys_get_temp_dir()]))->createContext();
new TempFile(sys_get_temp_dir().'/fs_test_queue');
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->fsContext->close();
}
diff --git a/pkg/fs/Tests/Functional/FsContextTest.php b/pkg/fs/Tests/Functional/FsContextTest.php
index bdcfb341a..806b9f56a 100644
--- a/pkg/fs/Tests/Functional/FsContextTest.php
+++ b/pkg/fs/Tests/Functional/FsContextTest.php
@@ -14,7 +14,7 @@ class FsContextTest extends TestCase
*/
private $fsContext;
- public function tearDown()
+ protected function tearDown(): void
{
$fs = new Filesystem();
$fs->remove(sys_get_temp_dir().'/enqueue');
diff --git a/pkg/fs/Tests/Functional/FsProducerTest.php b/pkg/fs/Tests/Functional/FsProducerTest.php
index 634e09882..75625cfdd 100644
--- a/pkg/fs/Tests/Functional/FsProducerTest.php
+++ b/pkg/fs/Tests/Functional/FsProducerTest.php
@@ -14,7 +14,7 @@ class FsProducerTest extends TestCase
*/
private $fsContext;
- public function setUp()
+ protected function setUp(): void
{
$this->fsContext = (new FsConnectionFactory(['path' => sys_get_temp_dir()]))->createContext();
@@ -22,7 +22,7 @@ public function setUp()
file_put_contents(sys_get_temp_dir().'/fs_test_queue', '');
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->fsContext->close();
}
diff --git a/pkg/fs/Tests/Functional/FsRpcUseCasesTest.php b/pkg/fs/Tests/Functional/FsRpcUseCasesTest.php
index 91c40f450..3a0327d7c 100644
--- a/pkg/fs/Tests/Functional/FsRpcUseCasesTest.php
+++ b/pkg/fs/Tests/Functional/FsRpcUseCasesTest.php
@@ -20,7 +20,7 @@ class FsRpcUseCasesTest extends TestCase
*/
private $fsContext;
- public function setUp()
+ protected function setUp(): void
{
$this->fsContext = (new FsConnectionFactory(['path' => sys_get_temp_dir()]))->createContext();
@@ -28,7 +28,7 @@ public function setUp()
new TempFile(sys_get_temp_dir().'/fs_reply_queue');
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->fsContext->close();
}
diff --git a/pkg/fs/Tests/LegacyFilesystemLockTest.php b/pkg/fs/Tests/LegacyFilesystemLockTest.php
index 77d729886..519712881 100644
--- a/pkg/fs/Tests/LegacyFilesystemLockTest.php
+++ b/pkg/fs/Tests/LegacyFilesystemLockTest.php
@@ -6,12 +6,14 @@
use Enqueue\Fs\LegacyFilesystemLock;
use Enqueue\Fs\Lock;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use Makasim\File\TempFile;
use PHPUnit\Framework\TestCase;
class LegacyFilesystemLockTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testShouldImplementLockInterface()
{
diff --git a/pkg/fs/Tests/Spec/FsMessageTest.php b/pkg/fs/Tests/Spec/FsMessageTest.php
index 20dd4beca..f1ece8ecb 100644
--- a/pkg/fs/Tests/Spec/FsMessageTest.php
+++ b/pkg/fs/Tests/Spec/FsMessageTest.php
@@ -7,9 +7,6 @@
class FsMessageTest extends MessageSpec
{
- /**
- * {@inheritdoc}
- */
protected function createMessage()
{
return new FsMessage();
diff --git a/pkg/fs/Tests/Spec/FsSendAndReceiveTimeToLiveMessagesFromQueueTest.php b/pkg/fs/Tests/Spec/FsSendAndReceiveTimeToLiveMessagesFromQueueTest.php
index 3dd1697c7..d6a76ca94 100644
--- a/pkg/fs/Tests/Spec/FsSendAndReceiveTimeToLiveMessagesFromQueueTest.php
+++ b/pkg/fs/Tests/Spec/FsSendAndReceiveTimeToLiveMessagesFromQueueTest.php
@@ -9,8 +9,6 @@
class FsSendAndReceiveTimeToLiveMessagesFromQueueTest extends SendAndReceiveTimeToLiveMessagesFromQueueSpec
{
/**
- * {@inheritdoc}
- *
* @return FsContext
*/
protected function createContext()
diff --git a/pkg/fs/composer.json b/pkg/fs/composer.json
index b0328b168..f84bc6932 100644
--- a/pkg/fs/composer.json
+++ b/pkg/fs/composer.json
@@ -6,17 +6,19 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "queue-interop/queue-interop": "0.7.x-dev",
- "symfony/filesystem": "^3.4|^4",
+ "php": "^8.1",
+ "queue-interop/queue-interop": "^0.8",
+ "enqueue/dsn": "^0.10",
+ "symfony/filesystem": "^7.0|^8.0",
"makasim/temp-file": "^0.2@stable"
},
"require-dev": {
- "phpunit/phpunit": "~5.5",
- "enqueue/null": "0.9.x-dev",
- "enqueue/test": "0.9.x-dev",
- "queue-interop/queue-spec": "0.6.x-dev",
- "symfony/dependency-injection": "^3.4|^4"
+ "phpunit/phpunit": "^9.5",
+ "enqueue/null": "0.10.x-dev",
+ "enqueue/test": "0.10.x-dev",
+ "queue-interop/queue-spec": "^0.6.2",
+ "symfony/dependency-injection": "^7.0|^8.0",
+ "symfony/yaml": "^7.0|^8.0"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -34,7 +36,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/fs/phpunit.xml.dist b/pkg/fs/phpunit.xml.dist
index 9754bd41f..79088ae1d 100644
--- a/pkg/fs/phpunit.xml.dist
+++ b/pkg/fs/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/gearman/.gitattributes b/pkg/gearman/.gitattributes
new file mode 100644
index 000000000..e55879e9d
--- /dev/null
+++ b/pkg/gearman/.gitattributes
@@ -0,0 +1,4 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/gearman/.github/workflows/ci.yml b/pkg/gearman/.github/workflows/ci.yml
new file mode 100644
index 000000000..668c25b7f
--- /dev/null
+++ b/pkg/gearman/.github/workflows/ci.yml
@@ -0,0 +1,30 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+ extensions: gearman
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/gearman/.travis.yml b/pkg/gearman/.travis.yml
deleted file mode 100644
index ca78987eb..000000000
--- a/pkg/gearman/.travis.yml
+++ /dev/null
@@ -1,32 +0,0 @@
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
- - '7.2'
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - sudo apt-get update
- - sudo apt-get install libgearman-dev -y --no-install-recommends --no-install-suggests
- - export GEARMAN_PACKAGE=gearman-2.0.3
- - curl -L -O https://github.com/wcgallego/pecl-gearman/archive/$GEARMAN_PACKAGE.tar.gz
- - tar zxvf $GEARMAN_PACKAGE.tar.gz
- - pushd pecl-gearman-$GEARMAN_PACKAGE
- - phpize
- - ./configure
- - make
- - make install
- - echo 'extension=gearman.so' > gearman.ini
- - phpenv config-add gearman.ini
- - popd
- - composer self-update
- - composer install --prefer-source
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/gearman/GearmanConsumer.php b/pkg/gearman/GearmanConsumer.php
index 7d4bcef23..e834fe469 100644
--- a/pkg/gearman/GearmanConsumer.php
+++ b/pkg/gearman/GearmanConsumer.php
@@ -25,12 +25,21 @@ class GearmanConsumer implements Consumer
*/
private $context;
+ /**
+ * Message content.
+ */
+ private $message;
+
public function __construct(GearmanContext $context, GearmanDestination $destination)
{
$this->context = $context;
$this->destination = $destination;
$this->worker = $context->createWorker();
+
+ $this->worker->addFunction($this->destination->getName(), function (\GearmanJob $job) {
+ $this->message = GearmanMessage::jsonUnserialize($job->workload());
+ });
}
/**
@@ -53,18 +62,14 @@ public function receive(int $timeout = 0): ?Message
$this->worker->setTimeout($timeout);
try {
- $message = null;
-
- $this->worker->addFunction($this->destination->getName(), function (\GearmanJob $job) use (&$message) {
- $message = GearmanMessage::jsonUnserialize($job->workload());
- });
+ $this->message = null;
- while ($this->worker->work());
+ $this->worker->work();
} finally {
restore_error_handler();
}
- return $message;
+ return $this->message;
}
/**
diff --git a/pkg/gearman/GearmanMessage.php b/pkg/gearman/GearmanMessage.php
index 625566d62..ee93a78dd 100644
--- a/pkg/gearman/GearmanMessage.php
+++ b/pkg/gearman/GearmanMessage.php
@@ -101,7 +101,7 @@ public function setRedelivered(bool $redelivered): void
$this->redelivered = $redelivered;
}
- public function setCorrelationId(string $correlationId = null): void
+ public function setCorrelationId(?string $correlationId = null): void
{
$this->setHeader('correlation_id', (string) $correlationId);
}
@@ -111,7 +111,7 @@ public function getCorrelationId(): ?string
return $this->getHeader('correlation_id');
}
- public function setMessageId(string $messageId = null): void
+ public function setMessageId(?string $messageId = null): void
{
$this->setHeader('message_id', (string) $messageId);
}
@@ -128,12 +128,12 @@ public function getTimestamp(): ?int
return null === $value ? null : (int) $value;
}
- public function setTimestamp(int $timestamp = null): void
+ public function setTimestamp(?int $timestamp = null): void
{
$this->setHeader('timestamp', $timestamp);
}
- public function setReplyTo(string $replyTo = null): void
+ public function setReplyTo(?string $replyTo = null): void
{
$this->setHeader('reply_to', $replyTo);
}
@@ -155,12 +155,8 @@ public function jsonSerialize(): array
public static function jsonUnserialize(string $json): self
{
$data = json_decode($json, true);
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'The malformed json given. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
}
return new self($data['body'], $data['properties'], $data['headers']);
@@ -171,7 +167,7 @@ public function getJob(): ?\GearmanJob
return $this->job;
}
- public function setJob(\GearmanJob $job = null): void
+ public function setJob(?\GearmanJob $job = null): void
{
$this->job = $job;
}
diff --git a/pkg/gearman/GearmanProducer.php b/pkg/gearman/GearmanProducer.php
index 83eaef3ae..870bdcb03 100644
--- a/pkg/gearman/GearmanProducer.php
+++ b/pkg/gearman/GearmanProducer.php
@@ -7,6 +7,7 @@
use Interop\Queue\Destination;
use Interop\Queue\Exception\InvalidDestinationException;
use Interop\Queue\Exception\InvalidMessageException;
+use Interop\Queue\Exception\PriorityNotSupportedException;
use Interop\Queue\Message;
use Interop\Queue\Producer;
@@ -39,7 +40,7 @@ public function send(Destination $destination, Message $message): void
}
}
- public function setDeliveryDelay(int $deliveryDelay = null): Producer
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
{
if (null === $deliveryDelay) {
return $this;
@@ -53,13 +54,13 @@ public function getDeliveryDelay(): ?int
return null;
}
- public function setPriority(int $priority = null): Producer
+ public function setPriority(?int $priority = null): Producer
{
if (null === $priority) {
return $this;
}
- throw new \LogicException('Not implemented');
+ throw PriorityNotSupportedException::providerDoestNotSupportIt();
}
public function getPriority(): ?int
@@ -67,7 +68,7 @@ public function getPriority(): ?int
return null;
}
- public function setTimeToLive(int $timeToLive = null): Producer
+ public function setTimeToLive(?int $timeToLive = null): Producer
{
if (null === $timeToLive) {
return $this;
diff --git a/pkg/gearman/README.md b/pkg/gearman/README.md
index d973ac841..444e0a128 100644
--- a/pkg/gearman/README.md
+++ b/pkg/gearman/README.md
@@ -1,27 +1,40 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Gearman Transport
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/gearman)
+[](https://github.com/php-enqueue/gearman/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/gearman)
[](https://packagist.org/packages/enqueue/gearman)
-
-This is an implementation of the queue specification. It allows you to send and consume message from Gearman broker.
+
+This is an implementation of the queue specification. It allows you to send and consume message from Gearman broker.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/transport/gearman/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
-It is released under the [MIT License](LICENSE).
\ No newline at end of file
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/gearman/Tests/GearmanConnectionFactoryConfigTest.php b/pkg/gearman/Tests/GearmanConnectionFactoryConfigTest.php
index bb8ab7ad6..8fc7a6b1e 100644
--- a/pkg/gearman/Tests/GearmanConnectionFactoryConfigTest.php
+++ b/pkg/gearman/Tests/GearmanConnectionFactoryConfigTest.php
@@ -4,6 +4,7 @@
use Enqueue\Gearman\GearmanConnectionFactory;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use PHPUnit\Framework\TestCase;
/**
@@ -12,6 +13,7 @@
class GearmanConnectionFactoryConfigTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
use SkipIfGearmanExtensionIsNotInstalledTrait;
public function testThrowNeitherArrayStringNorNullGivenAsConfig()
@@ -40,9 +42,6 @@ public function testThrowIfDsnCouldNotBeParsed()
/**
* @dataProvider provideConfigs
- *
- * @param mixed $config
- * @param mixed $expectedConfig
*/
public function testShouldParseConfigurationAsExpected($config, $expectedConfig)
{
diff --git a/pkg/gearman/Tests/GearmanContextTest.php b/pkg/gearman/Tests/GearmanContextTest.php
index 484ab00a0..8a36ad80b 100644
--- a/pkg/gearman/Tests/GearmanContextTest.php
+++ b/pkg/gearman/Tests/GearmanContextTest.php
@@ -12,6 +12,7 @@
/**
* @group functional
+ * @group gearman
*/
class GearmanContextTest extends TestCase
{
@@ -23,11 +24,6 @@ public function testShouldImplementContextInterface()
$this->assertClassImplements(Context::class, GearmanContext::class);
}
- public function testCouldBeConstructedWithConnectionConfigAsFirstArgument()
- {
- new GearmanContext(['host' => 'aHost', 'port' => 'aPort']);
- }
-
public function testThrowNotImplementedOnCreateTemporaryQueue()
{
$context = new GearmanContext(['host' => 'aHost', 'port' => 'aPort']);
diff --git a/pkg/gearman/Tests/GearmanProducerTest.php b/pkg/gearman/Tests/GearmanProducerTest.php
index 907d9ef46..2a7baa4de 100644
--- a/pkg/gearman/Tests/GearmanProducerTest.php
+++ b/pkg/gearman/Tests/GearmanProducerTest.php
@@ -10,6 +10,7 @@
use Enqueue\Test\ClassExtensionTrait;
use Interop\Queue\Exception\InvalidDestinationException;
use Interop\Queue\Exception\InvalidMessageException;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class GearmanProducerTest extends TestCase
@@ -17,11 +18,6 @@ class GearmanProducerTest extends TestCase
use ClassExtensionTrait;
use SkipIfGearmanExtensionIsNotInstalledTrait;
- public function testCouldBeConstructedWithGearmanClientAsFirstArgument()
- {
- new GearmanProducer($this->createGearmanClientMock());
- }
-
public function testThrowIfDestinationInvalid()
{
$producer = new GearmanProducer($this->createGearmanClientMock());
@@ -68,7 +64,7 @@ public function testShouldJsonEncodeMessageAndPutToExpectedTube()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|\GearmanClient
+ * @return MockObject|\GearmanClient
*/
private function createGearmanClientMock()
{
diff --git a/pkg/gearman/Tests/SkipIfGearmanExtensionIsNotInstalledTrait.php b/pkg/gearman/Tests/SkipIfGearmanExtensionIsNotInstalledTrait.php
index 99419eb15..9c680bb67 100644
--- a/pkg/gearman/Tests/SkipIfGearmanExtensionIsNotInstalledTrait.php
+++ b/pkg/gearman/Tests/SkipIfGearmanExtensionIsNotInstalledTrait.php
@@ -4,7 +4,7 @@
trait SkipIfGearmanExtensionIsNotInstalledTrait
{
- public function setUp()
+ public function setUp(): void
{
if (false == class_exists(\GearmanClient::class)) {
$this->markTestSkipped('The gearman extension is not installed');
diff --git a/pkg/gearman/Tests/Spec/GearmanConnectionFactoryTest.php b/pkg/gearman/Tests/Spec/GearmanConnectionFactoryTest.php
index 148bf66d2..05418febc 100644
--- a/pkg/gearman/Tests/Spec/GearmanConnectionFactoryTest.php
+++ b/pkg/gearman/Tests/Spec/GearmanConnectionFactoryTest.php
@@ -10,9 +10,6 @@ class GearmanConnectionFactoryTest extends ConnectionFactorySpec
{
use SkipIfGearmanExtensionIsNotInstalledTrait;
- /**
- * {@inheritdoc}
- */
protected function createConnectionFactory()
{
return new GearmanConnectionFactory();
diff --git a/pkg/gearman/Tests/Spec/GearmanContextTest.php b/pkg/gearman/Tests/Spec/GearmanContextTest.php
index 431465cc5..d5f879f12 100644
--- a/pkg/gearman/Tests/Spec/GearmanContextTest.php
+++ b/pkg/gearman/Tests/Spec/GearmanContextTest.php
@@ -7,12 +7,10 @@
/**
* @group functional
+ * @group gearman
*/
class GearmanContextTest extends ContextSpec
{
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return (new GearmanConnectionFactory(getenv('GEARMAN_DSN')))->createContext();
diff --git a/pkg/gearman/Tests/Spec/GearmanMessageTest.php b/pkg/gearman/Tests/Spec/GearmanMessageTest.php
index 7ad01d6db..37aa71e62 100644
--- a/pkg/gearman/Tests/Spec/GearmanMessageTest.php
+++ b/pkg/gearman/Tests/Spec/GearmanMessageTest.php
@@ -10,9 +10,6 @@ class GearmanMessageTest extends MessageSpec
{
use SkipIfGearmanExtensionIsNotInstalledTrait;
- /**
- * {@inheritdoc}
- */
protected function createMessage()
{
return new GearmanMessage();
diff --git a/pkg/gearman/Tests/Spec/GearmanQueueTest.php b/pkg/gearman/Tests/Spec/GearmanQueueTest.php
index 3d486849e..abf6be603 100644
--- a/pkg/gearman/Tests/Spec/GearmanQueueTest.php
+++ b/pkg/gearman/Tests/Spec/GearmanQueueTest.php
@@ -10,9 +10,6 @@ class GearmanQueueTest extends QueueSpec
{
use SkipIfGearmanExtensionIsNotInstalledTrait;
- /**
- * {@inheritdoc}
- */
protected function createQueue()
{
return new GearmanDestination(self::EXPECTED_QUEUE_NAME);
diff --git a/pkg/gearman/Tests/Spec/GearmanSendToAndReceiveFromQueueTest.php b/pkg/gearman/Tests/Spec/GearmanSendToAndReceiveFromQueueTest.php
index 80b13f8df..10a284987 100644
--- a/pkg/gearman/Tests/Spec/GearmanSendToAndReceiveFromQueueTest.php
+++ b/pkg/gearman/Tests/Spec/GearmanSendToAndReceiveFromQueueTest.php
@@ -9,12 +9,10 @@
/**
* @group functional
+ * @group gearman
*/
class GearmanSendToAndReceiveFromQueueTest extends SendToAndReceiveFromQueueSpec
{
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
$factory = new GearmanConnectionFactory(getenv('GEARMAN_DSN'));
@@ -23,8 +21,7 @@ protected function createContext()
}
/**
- * @param Context $context
- * @param string $queueName
+ * @param string $queueName
*
* @return Queue
*/
diff --git a/pkg/gearman/Tests/Spec/GearmanSendToAndReceiveNoWaitFromQueueTest.php b/pkg/gearman/Tests/Spec/GearmanSendToAndReceiveNoWaitFromQueueTest.php
index 590b8ede5..e2164ea7a 100644
--- a/pkg/gearman/Tests/Spec/GearmanSendToAndReceiveNoWaitFromQueueTest.php
+++ b/pkg/gearman/Tests/Spec/GearmanSendToAndReceiveNoWaitFromQueueTest.php
@@ -8,12 +8,10 @@
/**
* @group functional
+ * @group gearman
*/
class GearmanSendToAndReceiveNoWaitFromQueueTest extends SendToAndReceiveNoWaitFromQueueSpec
{
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
$factory = new GearmanConnectionFactory(getenv('GEARMAN_DSN'));
@@ -21,9 +19,6 @@ protected function createContext()
return $factory->createContext();
}
- /**
- * {@inheritdoc}
- */
protected function createQueue(Context $context, $queueName)
{
return $context->createQueue($queueName.time());
diff --git a/pkg/gearman/Tests/Spec/GearmanSendToTopicAndReceiveFromQueueTest.php b/pkg/gearman/Tests/Spec/GearmanSendToTopicAndReceiveFromQueueTest.php
index c90432e00..32463cce1 100644
--- a/pkg/gearman/Tests/Spec/GearmanSendToTopicAndReceiveFromQueueTest.php
+++ b/pkg/gearman/Tests/Spec/GearmanSendToTopicAndReceiveFromQueueTest.php
@@ -8,19 +8,17 @@
/**
* @group functional
+ * @group gearman
*/
class GearmanSendToTopicAndReceiveFromQueueTest extends SendToTopicAndReceiveFromQueueSpec
{
private $time;
- public function setUp()
+ protected function setUp(): void
{
$this->time = time();
}
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
$factory = new GearmanConnectionFactory(getenv('GEARMAN_DSN'));
@@ -28,17 +26,11 @@ protected function createContext()
return $factory->createContext();
}
- /**
- * {@inheritdoc}
- */
protected function createQueue(Context $context, $queueName)
{
return $context->createQueue($queueName.$this->time);
}
- /**
- * {@inheritdoc}
- */
protected function createTopic(Context $context, $topicName)
{
return $context->createTopic($topicName.$this->time);
diff --git a/pkg/gearman/Tests/Spec/GearmanSendToTopicAndReceiveNoWaitFromQueueTest.php b/pkg/gearman/Tests/Spec/GearmanSendToTopicAndReceiveNoWaitFromQueueTest.php
index 469f9e997..993dc3f25 100644
--- a/pkg/gearman/Tests/Spec/GearmanSendToTopicAndReceiveNoWaitFromQueueTest.php
+++ b/pkg/gearman/Tests/Spec/GearmanSendToTopicAndReceiveNoWaitFromQueueTest.php
@@ -8,19 +8,17 @@
/**
* @group functional
+ * @group gearman
*/
class GearmanSendToTopicAndReceiveNoWaitFromQueueTest extends SendToTopicAndReceiveNoWaitFromQueueSpec
{
private $time;
- public function setUp()
+ protected function setUp(): void
{
$this->time = time();
}
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
$factory = new GearmanConnectionFactory(getenv('GEARMAN_DSN'));
@@ -28,17 +26,11 @@ protected function createContext()
return $factory->createContext();
}
- /**
- * {@inheritdoc}
- */
protected function createQueue(Context $context, $queueName)
{
return $context->createQueue($queueName.$this->time);
}
- /**
- * {@inheritdoc}
- */
protected function createTopic(Context $context, $topicName)
{
return $context->createTopic($topicName.$this->time);
diff --git a/pkg/gearman/Tests/Spec/GearmanTopicTest.php b/pkg/gearman/Tests/Spec/GearmanTopicTest.php
index 336c37f7d..826344e8b 100644
--- a/pkg/gearman/Tests/Spec/GearmanTopicTest.php
+++ b/pkg/gearman/Tests/Spec/GearmanTopicTest.php
@@ -10,9 +10,6 @@ class GearmanTopicTest extends TopicSpec
{
use SkipIfGearmanExtensionIsNotInstalledTrait;
- /**
- * {@inheritdoc}
- */
protected function createTopic()
{
return new GearmanDestination(self::EXPECTED_TOPIC_NAME);
diff --git a/pkg/gearman/composer.json b/pkg/gearman/composer.json
index 52750af3d..e8805849f 100644
--- a/pkg/gearman/composer.json
+++ b/pkg/gearman/composer.json
@@ -6,15 +6,15 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
+ "php": "^8.1",
"ext-gearman": "^2.0",
- "queue-interop/queue-interop": "0.7.x-dev"
+ "queue-interop/queue-interop": "^0.8"
},
"require-dev": {
- "phpunit/phpunit": "~5.4.0",
- "enqueue/test": "0.9.x-dev",
- "enqueue/null": "0.9.x-dev",
- "queue-interop/queue-spec": "0.6.x-dev"
+ "phpunit/phpunit": "^9.5",
+ "enqueue/test": "0.10.x-dev",
+ "enqueue/null": "0.10.x-dev",
+ "queue-interop/queue-spec": "^0.6.2"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -32,7 +32,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/gearman/phpunit.xml.dist b/pkg/gearman/phpunit.xml.dist
index 626570c00..6b750813c 100644
--- a/pkg/gearman/phpunit.xml.dist
+++ b/pkg/gearman/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/gps/.gitattributes b/pkg/gps/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/gps/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/gps/.github/workflows/ci.yml b/pkg/gps/.github/workflows/ci.yml
new file mode 100644
index 000000000..c91cb39ab
--- /dev/null
+++ b/pkg/gps/.github/workflows/ci.yml
@@ -0,0 +1,29 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/gps/.travis.yml b/pkg/gps/.travis.yml
deleted file mode 100644
index 9ed4fa123..000000000
--- a/pkg/gps/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-sudo: false
-
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
- - '7.2'
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - composer self-update
- - composer install --prefer-source
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/gps/GpsConnectionFactory.php b/pkg/gps/GpsConnectionFactory.php
index bc4a0a52a..e45f8cbe3 100644
--- a/pkg/gps/GpsConnectionFactory.php
+++ b/pkg/gps/GpsConnectionFactory.php
@@ -85,23 +85,20 @@ public function createContext(): Context
private function parseDsn(string $dsn): array
{
- $dsn = new Dsn($dsn);
+ $dsn = Dsn::parseFirst($dsn);
if ('gps' !== $dsn->getSchemeProtocol()) {
- throw new \LogicException(sprintf(
- 'The given scheme protocol "%s" is not supported. It must be "gps"',
- $dsn->getSchemeProtocol()
- ));
+ throw new \LogicException(sprintf('The given scheme protocol "%s" is not supported. It must be "gps"', $dsn->getSchemeProtocol()));
}
- $emulatorHost = $dsn->getQueryParameter('emulatorHost');
+ $emulatorHost = $dsn->getString('emulatorHost');
$hasEmulator = $emulatorHost ? true : null;
return array_filter(array_replace($dsn->getQuery(), [
- 'projectId' => $dsn->getQueryParameter('projectId'),
- 'keyFilePath' => $dsn->getQueryParameter('keyFilePath'),
- 'retries' => $dsn->getInt('retries'),
- 'scopes' => $dsn->getQueryParameter('scopes'),
+ 'projectId' => $dsn->getString('projectId'),
+ 'keyFilePath' => $dsn->getString('keyFilePath'),
+ 'retries' => $dsn->getDecimal('retries'),
+ 'scopes' => $dsn->getString('scopes'),
'emulatorHost' => $emulatorHost,
'hasEmulator' => $hasEmulator,
'lazy' => $dsn->getBool('lazy'),
diff --git a/pkg/gps/GpsContext.php b/pkg/gps/GpsContext.php
index 77e6200cf..27625992a 100644
--- a/pkg/gps/GpsContext.php
+++ b/pkg/gps/GpsContext.php
@@ -52,11 +52,7 @@ public function __construct($client, array $options = [])
} elseif (is_callable($client)) {
$this->clientFactory = $client;
} else {
- throw new \InvalidArgumentException(sprintf(
- 'The $client argument must be either %s or callable that returns %s once called.',
- PubSubClient::class,
- PubSubClient::class
- ));
+ throw new \InvalidArgumentException(sprintf('The $client argument must be either %s or callable that returns %s once called.', PubSubClient::class, PubSubClient::class));
}
}
@@ -148,11 +144,7 @@ public function getClient(): PubSubClient
if (false == $this->client) {
$client = call_user_func($this->clientFactory);
if (false == $client instanceof PubSubClient) {
- throw new \LogicException(sprintf(
- 'The factory must return instance of %s. It returned %s',
- PubSubClient::class,
- is_object($client) ? get_class($client) : gettype($client)
- ));
+ throw new \LogicException(sprintf('The factory must return instance of %s. It returned %s', PubSubClient::class, is_object($client) ? $client::class : gettype($client)));
}
$this->client = $client;
diff --git a/pkg/gps/GpsMessage.php b/pkg/gps/GpsMessage.php
index 5e83e078c..b7e2bf484 100644
--- a/pkg/gps/GpsMessage.php
+++ b/pkg/gps/GpsMessage.php
@@ -103,7 +103,7 @@ public function isRedelivered(): bool
return $this->redelivered;
}
- public function setCorrelationId(string $correlationId = null): void
+ public function setCorrelationId(?string $correlationId = null): void
{
$this->setHeader('correlation_id', $correlationId);
}
@@ -113,7 +113,7 @@ public function getCorrelationId(): ?string
return $this->getHeader('correlation_id');
}
- public function setMessageId(string $messageId = null): void
+ public function setMessageId(?string $messageId = null): void
{
$this->setHeader('message_id', $messageId);
}
@@ -130,12 +130,12 @@ public function getTimestamp(): ?int
return null === $value ? null : (int) $value;
}
- public function setTimestamp(int $timestamp = null): void
+ public function setTimestamp(?int $timestamp = null): void
{
$this->setHeader('timestamp', $timestamp);
}
- public function setReplyTo(string $replyTo = null): void
+ public function setReplyTo(?string $replyTo = null): void
{
$this->setHeader('reply_to', $replyTo);
}
@@ -157,15 +157,11 @@ public function jsonSerialize(): array
public static function jsonUnserialize(string $json): self
{
$data = json_decode($json, true);
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'The malformed json given. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
}
- return new self($data['body'], $data['properties'], $data['headers']);
+ return new self($data['body'] ?? $json, $data['properties'] ?? [], $data['headers'] ?? []);
}
public function getNativeMessage(): ?GoogleMessage
@@ -173,7 +169,7 @@ public function getNativeMessage(): ?GoogleMessage
return $this->nativeMessage;
}
- public function setNativeMessage(GoogleMessage $message = null): void
+ public function setNativeMessage(?GoogleMessage $message = null): void
{
$this->nativeMessage = $message;
}
diff --git a/pkg/gps/GpsProducer.php b/pkg/gps/GpsProducer.php
index 86c9052c0..7e307636f 100644
--- a/pkg/gps/GpsProducer.php
+++ b/pkg/gps/GpsProducer.php
@@ -37,12 +37,17 @@ public function send(Destination $destination, Message $message): void
/** @var Topic $topic */
$topic = $this->context->getClient()->topic($destination->getTopicName());
- $topic->publish([
- 'data' => json_encode($message),
- ]);
+
+ $params = ['data' => json_encode($message)];
+
+ if (count($message->getHeaders()) > 0) {
+ $params['attributes'] = $message->getHeaders();
+ }
+
+ $topic->publish($params);
}
- public function setDeliveryDelay(int $deliveryDelay = null): Producer
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
{
if (null === $deliveryDelay) {
return $this;
@@ -56,7 +61,7 @@ public function getDeliveryDelay(): ?int
return null;
}
- public function setPriority(int $priority = null): Producer
+ public function setPriority(?int $priority = null): Producer
{
if (null === $priority) {
return $this;
@@ -70,7 +75,7 @@ public function getPriority(): ?int
return null;
}
- public function setTimeToLive(int $timeToLive = null): Producer
+ public function setTimeToLive(?int $timeToLive = null): Producer
{
if (null === $timeToLive) {
return $this;
diff --git a/pkg/gps/README.md b/pkg/gps/README.md
index f7ecff23e..4f2a0e6ac 100644
--- a/pkg/gps/README.md
+++ b/pkg/gps/README.md
@@ -1,19 +1,28 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Google Pub/Sub Transport
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/gps)
+[](https://github.com/php-enqueue/gps/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/gps)
[](https://packagist.org/packages/enqueue/gps)
-
-This is an implementation of Queue Interop specification. It allows you to send and consume message through Google Pub/Sub library.
+
+This is an implementation of Queue Interop specification. It allows you to send and consume message through Google Pub/Sub library.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/transport/gps/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
## License
-It is released under the [MIT License](LICENSE).
\ No newline at end of file
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/gps/Tests/GpsConnectionFactoryConfigTest.php b/pkg/gps/Tests/GpsConnectionFactoryConfigTest.php
index a1700f64f..474149497 100644
--- a/pkg/gps/Tests/GpsConnectionFactoryConfigTest.php
+++ b/pkg/gps/Tests/GpsConnectionFactoryConfigTest.php
@@ -4,6 +4,7 @@
use Enqueue\Gps\GpsConnectionFactory;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use PHPUnit\Framework\TestCase;
/**
@@ -12,6 +13,7 @@
class GpsConnectionFactoryConfigTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testThrowNeitherArrayStringNorNullGivenAsConfig()
{
@@ -39,9 +41,6 @@ public function testThrowIfDsnCouldNotBeParsed()
/**
* @dataProvider provideConfigs
- *
- * @param mixed $config
- * @param mixed $expectedConfig
*/
public function testShouldParseConfigurationAsExpected($config, $expectedConfig)
{
diff --git a/pkg/gps/Tests/GpsConsumerTest.php b/pkg/gps/Tests/GpsConsumerTest.php
index 24bed7e3b..0b4b925ce 100644
--- a/pkg/gps/Tests/GpsConsumerTest.php
+++ b/pkg/gps/Tests/GpsConsumerTest.php
@@ -180,7 +180,7 @@ public function testShouldReceiveMessage()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|GpsContext
+ * @return \PHPUnit\Framework\MockObject\MockObject|GpsContext
*/
private function createContextMock()
{
@@ -188,7 +188,7 @@ private function createContextMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|PubSubClient
+ * @return \PHPUnit\Framework\MockObject\MockObject|PubSubClient
*/
private function createPubSubClientMock()
{
@@ -196,7 +196,7 @@ private function createPubSubClientMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Subscription
+ * @return \PHPUnit\Framework\MockObject\MockObject|Subscription
*/
private function createSubscriptionMock()
{
diff --git a/pkg/gps/Tests/GpsContextTest.php b/pkg/gps/Tests/GpsContextTest.php
index 355eeff81..658e2659e 100644
--- a/pkg/gps/Tests/GpsContextTest.php
+++ b/pkg/gps/Tests/GpsContextTest.php
@@ -87,7 +87,7 @@ public function testCreateConsumerShouldThrowExceptionIfInvalidDestination()
}
/**
- * @return PubSubClient|\PHPUnit_Framework_MockObject_MockObject|PubSubClient
+ * @return PubSubClient|\PHPUnit\Framework\MockObject\MockObject|PubSubClient
*/
private function createPubSubClientMock()
{
diff --git a/pkg/gps/Tests/GpsMessageTest.php b/pkg/gps/Tests/GpsMessageTest.php
index d84cd99d9..8182333cc 100644
--- a/pkg/gps/Tests/GpsMessageTest.php
+++ b/pkg/gps/Tests/GpsMessageTest.php
@@ -29,7 +29,7 @@ public function testCouldBeUnserializedFromJson()
$json = json_encode($message);
- //guard
+ // guard
$this->assertNotEmpty($json);
$unserializedMessage = GpsMessage::jsonUnserialize($json);
@@ -38,6 +38,31 @@ public function testCouldBeUnserializedFromJson()
$this->assertEquals($message, $unserializedMessage);
}
+ public function testMessageEntityCouldBeUnserializedFromJson()
+ {
+ $json = '{"body":"theBody","properties":{"thePropFoo":"thePropFooVal"},"headers":{"theHeaderFoo":"theHeaderFooVal"}}';
+
+ $unserializedMessage = GpsMessage::jsonUnserialize($json);
+
+ $this->assertInstanceOf(GpsMessage::class, $unserializedMessage);
+ $decoded = json_decode($json, true);
+ $this->assertEquals($decoded['body'], $unserializedMessage->getBody());
+ $this->assertEquals($decoded['properties'], $unserializedMessage->getProperties());
+ $this->assertEquals($decoded['headers'], $unserializedMessage->getHeaders());
+ }
+
+ public function testMessagePayloadCouldBeUnserializedFromJson()
+ {
+ $json = '{"theBodyPropFoo":"theBodyPropVal"}';
+
+ $unserializedMessage = GpsMessage::jsonUnserialize($json);
+
+ $this->assertInstanceOf(GpsMessage::class, $unserializedMessage);
+ $this->assertEquals($json, $unserializedMessage->getBody());
+ $this->assertEquals([], $unserializedMessage->getProperties());
+ $this->assertEquals([], $unserializedMessage->getHeaders());
+ }
+
public function testThrowIfMalformedJsonGivenOnUnsterilizedFromJson()
{
$this->expectException(\InvalidArgumentException::class);
diff --git a/pkg/gps/Tests/GpsProducerTest.php b/pkg/gps/Tests/GpsProducerTest.php
index 6d3191bb8..3079d3c7c 100644
--- a/pkg/gps/Tests/GpsProducerTest.php
+++ b/pkg/gps/Tests/GpsProducerTest.php
@@ -33,7 +33,39 @@ public function testShouldSendMessage()
$gtopic
->expects($this->once())
->method('publish')
- ->with($this->identicalTo(['data' => '{"body":"","properties":[],"headers":[]}']))
+ ->with($this->identicalTo([
+ 'data' => '{"body":"","properties":[],"headers":[]}',
+ ]));
+
+ $client = $this->createPubSubClientMock();
+ $client
+ ->expects($this->once())
+ ->method('topic')
+ ->with('topic-name')
+ ->willReturn($gtopic)
+ ;
+
+ $context = $this->createContextMock();
+ $context
+ ->expects($this->once())
+ ->method('getClient')
+ ->willReturn($client)
+ ;
+
+ $producer = new GpsProducer($context);
+ $producer->send($topic, $message);
+ }
+
+ public function testShouldSendMessageWithHeaders()
+ {
+ $topic = new GpsTopic('topic-name');
+ $message = new GpsMessage('', [], ['key1' => 'value1']);
+
+ $gtopic = $this->createGTopicMock();
+ $gtopic
+ ->expects($this->once())
+ ->method('publish')
+ ->with($this->identicalTo(['data' => '{"body":"","properties":[],"headers":{"key1":"value1"}}', 'attributes' => ['key1' => 'value1']]))
;
$client = $this->createPubSubClientMock();
@@ -56,7 +88,7 @@ public function testShouldSendMessage()
}
/**
- * @return GpsContext|\PHPUnit_Framework_MockObject_MockObject|GpsContext
+ * @return GpsContext|\PHPUnit\Framework\MockObject\MockObject|GpsContext
*/
private function createContextMock()
{
@@ -64,7 +96,7 @@ private function createContextMock()
}
/**
- * @return PubSubClient|\PHPUnit_Framework_MockObject_MockObject|PubSubClient
+ * @return PubSubClient|\PHPUnit\Framework\MockObject\MockObject|PubSubClient
*/
private function createPubSubClientMock()
{
@@ -72,7 +104,7 @@ private function createPubSubClientMock()
}
/**
- * @return Topic|\PHPUnit_Framework_MockObject_MockObject|Topic
+ * @return Topic|\PHPUnit\Framework\MockObject\MockObject|Topic
*/
private function createGTopicMock()
{
diff --git a/pkg/gps/Tests/Spec/GpsSendToTopicAndReceiveFromQueueTest.php b/pkg/gps/Tests/Spec/GpsSendToTopicAndReceiveFromQueueTest.php
index 30485b072..4bcaf357b 100644
--- a/pkg/gps/Tests/Spec/GpsSendToTopicAndReceiveFromQueueTest.php
+++ b/pkg/gps/Tests/Spec/GpsSendToTopicAndReceiveFromQueueTest.php
@@ -23,7 +23,6 @@ protected function createContext()
/**
* @param GpsContext $context
- * @param mixed $queueName
*/
protected function createQueue(Context $context, $queueName)
{
diff --git a/pkg/gps/Tests/Spec/GpsSendToTopicAndReceiveNoWaitFromQueueTest.php b/pkg/gps/Tests/Spec/GpsSendToTopicAndReceiveNoWaitFromQueueTest.php
index 240c71a3b..3a96bb533 100644
--- a/pkg/gps/Tests/Spec/GpsSendToTopicAndReceiveNoWaitFromQueueTest.php
+++ b/pkg/gps/Tests/Spec/GpsSendToTopicAndReceiveNoWaitFromQueueTest.php
@@ -23,7 +23,6 @@ protected function createContext()
/**
* @param GpsContext $context
- * @param mixed $queueName
*/
protected function createQueue(Context $context, $queueName)
{
diff --git a/pkg/gps/composer.json b/pkg/gps/composer.json
index aede85d7f..e7654be8d 100644
--- a/pkg/gps/composer.json
+++ b/pkg/gps/composer.json
@@ -6,15 +6,15 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "queue-interop/queue-interop": "0.7.x-dev",
- "google/cloud-pubsub": "^1.0",
- "enqueue/dsn": "0.9.x-dev"
+ "php": "^8.1",
+ "queue-interop/queue-interop": "^0.8",
+ "google/cloud-pubsub": "^1.4.3",
+ "enqueue/dsn": "^0.10"
},
"require-dev": {
- "phpunit/phpunit": "~5.4.0",
- "enqueue/test": "0.9.x-dev",
- "queue-interop/queue-spec": "0.6.x-dev"
+ "phpunit/phpunit": "^9.5",
+ "enqueue/test": "0.10.x-dev",
+ "queue-interop/queue-spec": "^0.6.2"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -32,7 +32,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/gps/phpunit.xml.dist b/pkg/gps/phpunit.xml.dist
index 57e46d2f2..77f02571a 100644
--- a/pkg/gps/phpunit.xml.dist
+++ b/pkg/gps/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/job-queue/.gitattributes b/pkg/job-queue/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/job-queue/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/job-queue/.github/workflows/ci.yml b/pkg/job-queue/.github/workflows/ci.yml
new file mode 100644
index 000000000..e6b79cb2d
--- /dev/null
+++ b/pkg/job-queue/.github/workflows/ci.yml
@@ -0,0 +1,29 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-dist"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/job-queue/.travis.yml b/pkg/job-queue/.travis.yml
deleted file mode 100644
index e74d70f07..000000000
--- a/pkg/job-queue/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-sudo: false
-
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
- - '7.2'
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - composer self-update
- - travis_retry composer install --prefer-dist
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/job-queue/CalculateRootJobStatusProcessor.php b/pkg/job-queue/CalculateRootJobStatusProcessor.php
index b9b0c4dfb..96e7db2e8 100644
--- a/pkg/job-queue/CalculateRootJobStatusProcessor.php
+++ b/pkg/job-queue/CalculateRootJobStatusProcessor.php
@@ -38,7 +38,7 @@ public function __construct(
JobStorage $jobStorage,
CalculateRootJobStatusService $calculateRootJobStatusCase,
ProducerInterface $producer,
- LoggerInterface $logger
+ LoggerInterface $logger,
) {
$this->jobStorage = $jobStorage;
$this->calculateRootJobStatusService = $calculateRootJobStatusCase;
diff --git a/pkg/job-queue/CalculateRootJobStatusService.php b/pkg/job-queue/CalculateRootJobStatusService.php
index af4631e2a..41dd350b9 100644
--- a/pkg/job-queue/CalculateRootJobStatusService.php
+++ b/pkg/job-queue/CalculateRootJobStatusService.php
@@ -12,17 +12,12 @@ class CalculateRootJobStatusService
*/
private $jobStorage;
- /**
- * @param JobStorage $jobStorage
- */
public function __construct(JobStorage $jobStorage)
{
$this->jobStorage = $jobStorage;
}
/**
- * @param Job $job
- *
* @return bool true if root job was stopped
*/
public function calculate(Job $job)
@@ -74,6 +69,7 @@ protected function calculateRootJobStatus(array $jobs)
$success = 0;
foreach ($jobs as $job) {
+ $this->jobStorage->refreshJobEntity($job);
switch ($job->getStatus()) {
case Job::STATUS_NEW:
$new++;
@@ -91,11 +87,7 @@ protected function calculateRootJobStatus(array $jobs)
$success++;
break;
default:
- throw new \LogicException(sprintf(
- 'Got unsupported job status: id: "%s" status: "%s"',
- $job->getId(),
- $job->getStatus()
- ));
+ throw new \LogicException(sprintf('Got unsupported job status: id: "%s" status: "%s"', $job->getId(), $job->getStatus()));
}
}
diff --git a/pkg/job-queue/Commands.php b/pkg/job-queue/Commands.php
index 57966c30c..ae744c991 100644
--- a/pkg/job-queue/Commands.php
+++ b/pkg/job-queue/Commands.php
@@ -4,5 +4,5 @@
class Commands
{
- const CALCULATE_ROOT_JOB_STATUS = 'enqueue.message_queue.job.calculate_root_job_status';
+ public const CALCULATE_ROOT_JOB_STATUS = 'enqueue.message_queue.job.calculate_root_job_status';
}
diff --git a/pkg/job-queue/DependentJobContext.php b/pkg/job-queue/DependentJobContext.php
index 34deba656..04b898fd3 100644
--- a/pkg/job-queue/DependentJobContext.php
+++ b/pkg/job-queue/DependentJobContext.php
@@ -14,9 +14,6 @@ class DependentJobContext
*/
private $dependentJobs;
- /**
- * @param Job $job
- */
public function __construct(Job $job)
{
$this->job = $job;
diff --git a/pkg/job-queue/DependentJobProcessor.php b/pkg/job-queue/DependentJobProcessor.php
index 6126be08f..ac3055b5f 100644
--- a/pkg/job-queue/DependentJobProcessor.php
+++ b/pkg/job-queue/DependentJobProcessor.php
@@ -30,11 +30,6 @@ class DependentJobProcessor implements Processor, TopicSubscriberInterface
*/
private $logger;
- /**
- * @param JobStorage $jobStorage
- * @param ProducerInterface $producer
- * @param LoggerInterface $logger
- */
public function __construct(JobStorage $jobStorage, ProducerInterface $producer, LoggerInterface $logger)
{
$this->jobStorage = $jobStorage;
@@ -42,9 +37,6 @@ public function __construct(JobStorage $jobStorage, ProducerInterface $producer,
$this->logger = $logger;
}
- /**
- * {@inheritdoc}
- */
public function process(Message $message, Context $context)
{
$data = JSON::decode($message->getBody());
diff --git a/pkg/job-queue/DependentJobService.php b/pkg/job-queue/DependentJobService.php
index b6066d669..9ab500ba8 100644
--- a/pkg/job-queue/DependentJobService.php
+++ b/pkg/job-queue/DependentJobService.php
@@ -20,8 +20,6 @@ public function __construct(JobStorage $jobStorage)
}
/**
- * @param Job $job
- *
* @return DependentJobContext
*/
public function createDependentJobContext(Job $job)
@@ -29,16 +27,10 @@ public function createDependentJobContext(Job $job)
return new DependentJobContext($job);
}
- /**
- * @param DependentJobContext $context
- */
public function saveDependentJob(DependentJobContext $context)
{
if (!$context->getJob()->isRoot()) {
- throw new \LogicException(sprintf(
- 'Only root jobs allowed but got child. jobId: "%s"',
- $context->getJob()->getId()
- ));
+ throw new \LogicException(sprintf('Only root jobs allowed but got child. jobId: "%s"', $context->getJob()->getId()));
}
$this->jobStorage->saveJob($context->getJob(), function (Job $job) use ($context) {
diff --git a/pkg/job-queue/Doctrine/JobStorage.php b/pkg/job-queue/Doctrine/JobStorage.php
index c84c284e6..a68cc52b3 100644
--- a/pkg/job-queue/Doctrine/JobStorage.php
+++ b/pkg/job-queue/Doctrine/JobStorage.php
@@ -2,12 +2,12 @@
namespace Enqueue\JobQueue\Doctrine;
-use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\DBAL\LockMode;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
+use Doctrine\Persistence\ManagerRegistry;
use Enqueue\JobQueue\DuplicateJobException;
use Enqueue\JobQueue\Job;
@@ -39,9 +39,8 @@ class JobStorage
private $uniqueTableName;
/**
- * @param ManagerRegistry $doctrine
- * @param string $entityClass
- * @param string $uniqueTableName
+ * @param string $entityClass
+ * @param string $uniqueTableName
*/
public function __construct(ManagerRegistry $doctrine, $entityClass, $uniqueTableName)
{
@@ -59,13 +58,18 @@ public function findJobById($id)
{
$qb = $this->getEntityRepository()->createQueryBuilder('job');
- return $qb
+ $job = $qb
->addSelect('rootJob')
->leftJoin('job.rootJob', 'rootJob')
->where('job = :id')
->setParameter('id', $id)
->getQuery()->getOneOrNullResult()
;
+ if ($job) {
+ $this->refreshJobEntity($job);
+ }
+
+ return $job;
}
/**
@@ -90,7 +94,6 @@ public function findRootJobByOwnerIdAndJobName($ownerId, $jobName)
/**
* @param string $name
- * @param Job $rootJob
*
* @return Job
*/
@@ -119,20 +122,13 @@ public function createJob()
}
/**
- * @param Job $job
- * @param \Closure|null $lockCallback
- *
* @throws DuplicateJobException
*/
- public function saveJob(Job $job, \Closure $lockCallback = null)
+ public function saveJob(Job $job, ?\Closure $lockCallback = null)
{
$class = $this->getEntityRepository()->getClassName();
if (!$job instanceof $class) {
- throw new \LogicException(sprintf(
- 'Got unexpected job instance: expected: "%s", actual" "%s"',
- $class,
- get_class($job)
- ));
+ throw new \LogicException(sprintf('Got unexpected job instance: expected: "%s", actual" "%s"', $class, $job::class));
}
if ($lockCallback) {
@@ -140,7 +136,7 @@ public function saveJob(Job $job, \Closure $lockCallback = null)
throw new \LogicException('Is not possible to create new job with lock, only update is allowed');
}
- $this->getEntityManager()->transactional(function (EntityManager $em) use ($job, $lockCallback) {
+ $this->getEntityManager()->wrapInTransaction(function (EntityManager $em) use ($job, $lockCallback) {
/** @var Job $job */
$job = $this->getEntityRepository()->find($job->getId(), LockMode::PESSIMISTIC_WRITE);
@@ -175,11 +171,7 @@ public function saveJob(Job $job, \Closure $lockCallback = null)
]);
}
} catch (UniqueConstraintViolationException $e) {
- throw new DuplicateJobException(sprintf(
- 'Duplicate job. ownerId:"%s", name:"%s"',
- $job->getOwnerId(),
- $job->getName()
- ));
+ throw new DuplicateJobException(sprintf('Duplicate job. ownerId:"%s", name:"%s"', $job->getOwnerId(), $job->getName()));
}
$this->getEntityManager()->persist($job);
@@ -192,6 +184,14 @@ public function saveJob(Job $job, \Closure $lockCallback = null)
}
}
+ /**
+ * @param Job $job
+ */
+ public function refreshJobEntity($job)
+ {
+ $this->getEntityManager()->refresh($job);
+ }
+
/**
* @return EntityRepository
*/
@@ -212,6 +212,9 @@ private function getEntityManager()
if (!$this->em) {
$this->em = $this->doctrine->getManagerForClass($this->entityClass);
}
+ if (!$this->em->isOpen()) {
+ $this->em = $this->doctrine->resetManager();
+ }
return $this->em;
}
diff --git a/pkg/job-queue/Doctrine/mapping/Job.orm.xml b/pkg/job-queue/Doctrine/mapping/Job.orm.xml
index e6fcbdde5..d6f481562 100644
--- a/pkg/job-queue/Doctrine/mapping/Job.orm.xml
+++ b/pkg/job-queue/Doctrine/mapping/Job.orm.xml
@@ -12,7 +12,7 @@
-
+
diff --git a/pkg/job-queue/Job.php b/pkg/job-queue/Job.php
index 0468d7fdb..ddf53c2e3 100644
--- a/pkg/job-queue/Job.php
+++ b/pkg/job-queue/Job.php
@@ -4,11 +4,11 @@
class Job
{
- const STATUS_NEW = 'enqueue.job_queue.status.new';
- const STATUS_RUNNING = 'enqueue.job_queue.status.running';
- const STATUS_SUCCESS = 'enqueue.job_queue.status.success';
- const STATUS_FAILED = 'enqueue.job_queue.status.failed';
- const STATUS_CANCELLED = 'enqueue.job_queue.status.cancelled';
+ public const STATUS_NEW = 'enqueue.job_queue.status.new';
+ public const STATUS_RUNNING = 'enqueue.job_queue.status.running';
+ public const STATUS_SUCCESS = 'enqueue.job_queue.status.success';
+ public const STATUS_FAILED = 'enqueue.job_queue.status.failed';
+ public const STATUS_CANCELLED = 'enqueue.job_queue.status.cancelled';
/**
* @var int
@@ -216,8 +216,6 @@ public function getRootJob()
* Do not call from the outside.
*
* @internal
- *
- * @param Job $rootJob
*/
public function setRootJob(self $rootJob)
{
@@ -237,8 +235,6 @@ public function getCreatedAt()
* Do not call from the outside.
*
* @internal
- *
- * @param \DateTime $createdAt
*/
public function setCreatedAt(\DateTime $createdAt)
{
@@ -258,8 +254,6 @@ public function getStartedAt()
* Do not call from the outside.
*
* @internal
- *
- * @param \DateTime $startedAt
*/
public function setStartedAt(\DateTime $startedAt)
{
@@ -279,8 +273,6 @@ public function getStoppedAt()
* Do not call from the outside.
*
* @internal
- *
- * @param \DateTime $stoppedAt
*/
public function setStoppedAt(\DateTime $stoppedAt)
{
@@ -324,9 +316,6 @@ public function getData()
return $this->data;
}
- /**
- * @param array $data
- */
public function setData(array $data)
{
$this->data = $data;
diff --git a/pkg/job-queue/JobProcessor.php b/pkg/job-queue/JobProcessor.php
index 77c03eefe..06698f45c 100644
--- a/pkg/job-queue/JobProcessor.php
+++ b/pkg/job-queue/JobProcessor.php
@@ -17,10 +17,6 @@ class JobProcessor
*/
private $producer;
- /**
- * @param JobStorage $jobStorage
- * @param ProducerInterface $producer
- */
public function __construct(JobStorage $jobStorage, ProducerInterface $producer)
{
$this->jobStorage = $jobStorage;
@@ -74,7 +70,6 @@ public function findOrCreateRootJob($ownerId, $jobName, $unique = false)
/**
* @param string $jobName
- * @param Job $rootJob
*
* @return Job
*/
@@ -104,9 +99,6 @@ public function findOrCreateChildJob($jobName, Job $rootJob)
return $job;
}
- /**
- * @param Job $job
- */
public function startChildJob(Job $job)
{
if ($job->isRoot()) {
@@ -116,11 +108,7 @@ public function startChildJob(Job $job)
$job = $this->jobStorage->findJobById($job->getId());
if (Job::STATUS_NEW !== $job->getStatus()) {
- throw new \LogicException(sprintf(
- 'Can start only new jobs: id: "%s", status: "%s"',
- $job->getId(),
- $job->getStatus()
- ));
+ throw new \LogicException(sprintf('Can start only new jobs: id: "%s", status: "%s"', $job->getId(), $job->getStatus()));
}
$job->setStatus(Job::STATUS_RUNNING);
@@ -131,9 +119,6 @@ public function startChildJob(Job $job)
$this->sendCalculateRootJobStatusEvent($job);
}
- /**
- * @param Job $job
- */
public function successChildJob(Job $job)
{
if ($job->isRoot()) {
@@ -143,11 +128,7 @@ public function successChildJob(Job $job)
$job = $this->jobStorage->findJobById($job->getId());
if (Job::STATUS_RUNNING !== $job->getStatus()) {
- throw new \LogicException(sprintf(
- 'Can success only running jobs. id: "%s", status: "%s"',
- $job->getId(),
- $job->getStatus()
- ));
+ throw new \LogicException(sprintf('Can success only running jobs. id: "%s", status: "%s"', $job->getId(), $job->getStatus()));
}
$job->setStatus(Job::STATUS_SUCCESS);
@@ -158,9 +139,6 @@ public function successChildJob(Job $job)
$this->sendCalculateRootJobStatusEvent($job);
}
- /**
- * @param Job $job
- */
public function failChildJob(Job $job)
{
if ($job->isRoot()) {
@@ -170,11 +148,7 @@ public function failChildJob(Job $job)
$job = $this->jobStorage->findJobById($job->getId());
if (Job::STATUS_RUNNING !== $job->getStatus()) {
- throw new \LogicException(sprintf(
- 'Can fail only running jobs. id: "%s", status: "%s"',
- $job->getId(),
- $job->getStatus()
- ));
+ throw new \LogicException(sprintf('Can fail only running jobs. id: "%s", status: "%s"', $job->getId(), $job->getStatus()));
}
$job->setStatus(Job::STATUS_FAILED);
@@ -185,9 +159,6 @@ public function failChildJob(Job $job)
$this->sendCalculateRootJobStatusEvent($job);
}
- /**
- * @param Job $job
- */
public function cancelChildJob(Job $job)
{
if ($job->isRoot()) {
@@ -197,11 +168,7 @@ public function cancelChildJob(Job $job)
$job = $this->jobStorage->findJobById($job->getId());
if (!in_array($job->getStatus(), [Job::STATUS_NEW, Job::STATUS_RUNNING], true)) {
- throw new \LogicException(sprintf(
- 'Can cancel only new or running jobs. id: "%s", status: "%s"',
- $job->getId(),
- $job->getStatus()
- ));
+ throw new \LogicException(sprintf('Can cancel only new or running jobs. id: "%s", status: "%s"', $job->getId(), $job->getStatus()));
}
$job->setStatus(Job::STATUS_CANCELLED);
@@ -217,7 +184,6 @@ public function cancelChildJob(Job $job)
}
/**
- * @param Job $job
* @param bool $force
*/
public function interruptRootJob(Job $job, $force = false)
@@ -245,8 +211,6 @@ public function interruptRootJob(Job $job, $force = false)
/**
* @see https://github.com/php-enqueue/enqueue-dev/pull/222#issuecomment-336102749 See for rationale
- *
- * @param Job $job
*/
protected function saveJob(Job $job)
{
@@ -255,12 +219,10 @@ protected function saveJob(Job $job)
/**
* @see https://github.com/php-enqueue/enqueue-dev/pull/222#issuecomment-336102749 See for rationale
- *
- * @param Job $job
*/
protected function sendCalculateRootJobStatusEvent(Job $job)
{
- $this->producer->sendEvent(Commands::CALCULATE_ROOT_JOB_STATUS, [
+ $this->producer->sendCommand(Commands::CALCULATE_ROOT_JOB_STATUS, [
'jobId' => $job->getId(),
]);
}
diff --git a/pkg/job-queue/JobRunner.php b/pkg/job-queue/JobRunner.php
index afd445c67..e21e524d6 100644
--- a/pkg/job-queue/JobRunner.php
+++ b/pkg/job-queue/JobRunner.php
@@ -14,24 +14,17 @@ class JobRunner
*/
private $rootJob;
- /**
- * @param JobProcessor $jobProcessor
- * @param Job $rootJob
- */
- public function __construct(JobProcessor $jobProcessor, Job $rootJob = null)
+ public function __construct(JobProcessor $jobProcessor, ?Job $rootJob = null)
{
$this->jobProcessor = $jobProcessor;
$this->rootJob = $rootJob;
}
/**
- * @param string $ownerId
- * @param string $name
- * @param callable $runCallback
+ * @param string $ownerId
+ * @param string $name
*
* @throws \Throwable|\Exception if $runCallback triggers an exception
- *
- * @return mixed
*/
public function runUnique($ownerId, $name, callable $runCallback)
{
@@ -54,11 +47,7 @@ public function runUnique($ownerId, $name, callable $runCallback)
try {
$this->jobProcessor->failChildJob($childJob);
} catch (\Throwable $t) {
- throw new OrphanJobException(sprintf(
- 'Job cleanup failed. ID: "%s" Name: "%s"',
- $childJob->getId(),
- $childJob->getName()
- ), 0, $e);
+ throw new OrphanJobException(sprintf('Job cleanup failed. ID: "%s" Name: "%s"', $childJob->getId(), $childJob->getName()), 0, $e);
}
throw $e;
@@ -74,10 +63,7 @@ public function runUnique($ownerId, $name, callable $runCallback)
}
/**
- * @param string $name
- * @param callable $startCallback
- *
- * @return mixed
+ * @param string $name
*/
public function createDelayed($name, callable $startCallback)
{
@@ -89,10 +75,7 @@ public function createDelayed($name, callable $startCallback)
}
/**
- * @param string $jobId
- * @param callable $runCallback
- *
- * @return mixed
+ * @param string $jobId
*/
public function runDelayed($jobId, callable $runCallback)
{
diff --git a/pkg/job-queue/README.md b/pkg/job-queue/README.md
index 5639a0486..6d237f53b 100644
--- a/pkg/job-queue/README.md
+++ b/pkg/job-queue/README.md
@@ -1,29 +1,42 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Job Queue.
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/job-queue)
+[](https://github.com/php-enqueue/job-queue/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/job-queue)
[](https://packagist.org/packages/enqueue/job-queue)
-
-There is job queue component build on top of a transport.
-It provides some additional features like: unique job, sub jobs, dependent job and so.
+
+There is job queue component build on top of a transport.
+It provides some additional features like: unique job, sub jobs, dependent job and so.
Read more about it in documentation
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
-It is released under the [MIT License](LICENSE).
\ No newline at end of file
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/job-queue/Test/DbalPersistedConnection.php b/pkg/job-queue/Test/DbalPersistedConnection.php
index 7c06f5ab0..512096acb 100644
--- a/pkg/job-queue/Test/DbalPersistedConnection.php
+++ b/pkg/job-queue/Test/DbalPersistedConnection.php
@@ -22,61 +22,37 @@ class DbalPersistedConnection extends Connection
*/
protected static $persistedTransactionNestingLevels;
- /**
- * {@inheritdoc}
- */
- public function connect()
+ public function connect(): DriverConnection
{
if ($this->isConnected()) {
- return false;
+ return $this->_conn;
}
if ($this->hasPersistedConnection()) {
$this->_conn = $this->getPersistedConnection();
- $this->setConnected(true);
} else {
parent::connect();
$this->persistConnection($this->_conn);
}
- return true;
+ return $this->_conn;
}
- /**
- * {@inheritdoc}
- */
- public function beginTransaction()
+ public function beginTransaction(): void
{
$this->wrapTransactionNestingLevel('beginTransaction');
}
- /**
- * {@inheritdoc}
- */
- public function commit()
+ public function commit(): void
{
$this->wrapTransactionNestingLevel('commit');
}
- /**
- * {@inheritdoc}
- */
- public function rollBack()
+ public function rollBack(): void
{
$this->wrapTransactionNestingLevel('rollBack');
}
- /**
- * @param bool $connected
- */
- protected function setConnected($connected)
- {
- $isConnected = new \ReflectionProperty('Doctrine\DBAL\Connection', '_isConnected');
- $isConnected->setAccessible(true);
- $isConnected->setValue($this, $connected);
- $isConnected->setAccessible(false);
- }
-
/**
* @return int
*/
@@ -97,9 +73,6 @@ protected function persistTransactionNestingLevel($level)
static::$persistedTransactionNestingLevels[$this->getConnectionId()] = $level;
}
- /**
- * @param DriverConnection $connection
- */
protected function persistConnection(DriverConnection $connection)
{
static::$persistedConnections[$this->getConnectionId()] = $connection;
@@ -134,10 +107,15 @@ protected function getConnectionId()
*/
private function setTransactionNestingLevel($level)
{
- $prop = new \ReflectionProperty('Doctrine\DBAL\Connection', '_transactionNestingLevel');
- $prop->setAccessible(true);
-
- return $prop->setValue($this, $level);
+ $rc = new \ReflectionClass(Connection::class);
+ $rp = $rc->hasProperty('transactionNestingLevel') ?
+ $rc->getProperty('transactionNestingLevel') :
+ $rc->getProperty('_transactionNestingLevel')
+ ;
+
+ $rp->setAccessible(true);
+ $rp->setValue($this, $level);
+ $rp->setAccessible(false);
}
/**
diff --git a/pkg/job-queue/Test/JobRunner.php b/pkg/job-queue/Test/JobRunner.php
index 62d9f9a52..6194fbcee 100644
--- a/pkg/job-queue/Test/JobRunner.php
+++ b/pkg/job-queue/Test/JobRunner.php
@@ -26,9 +26,6 @@ public function __construct()
{
}
- /**
- * {@inheritdoc}
- */
public function runUnique($ownerId, $jobName, \Closure $runCallback)
{
$this->runUniqueJobs[] = ['ownerId' => $ownerId, 'jobName' => $jobName, 'runCallback' => $runCallback];
@@ -36,11 +33,6 @@ public function runUnique($ownerId, $jobName, \Closure $runCallback)
return call_user_func($runCallback, $this, new Job());
}
- /**
- * {@inheritdoc}
- *
- * @return mixed
- */
public function createDelayed($jobName, \Closure $startCallback)
{
$this->createDelayedJobs[] = ['jobName' => $jobName, 'runCallback' => $startCallback];
@@ -48,11 +40,6 @@ public function createDelayed($jobName, \Closure $startCallback)
return call_user_func($startCallback, $this, new Job());
}
- /**
- * {@inheritdoc}
- *
- * @return mixed
- */
public function runDelayed($jobId, \Closure $runCallback)
{
$this->runDelayedJobs[] = ['jobId' => $jobId, 'runCallback' => $runCallback];
diff --git a/pkg/job-queue/Tests/CalculateRootJobStatusProcessorTest.php b/pkg/job-queue/Tests/CalculateRootJobStatusProcessorTest.php
index fe260bad9..8509f0544 100644
--- a/pkg/job-queue/Tests/CalculateRootJobStatusProcessorTest.php
+++ b/pkg/job-queue/Tests/CalculateRootJobStatusProcessorTest.php
@@ -12,20 +12,11 @@
use Enqueue\JobQueue\Topics;
use Enqueue\Null\NullMessage;
use Interop\Queue\Context;
+use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
class CalculateRootJobStatusProcessorTest extends \PHPUnit\Framework\TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new CalculateRootJobStatusProcessor(
- $this->createJobStorageMock(),
- $this->createCalculateRootJobStatusCaseMock(),
- $this->createProducerMock(),
- $this->createLoggerMock()
- );
- }
-
public function testShouldReturnSubscribedTopicNames()
{
$this->assertEquals(
@@ -103,7 +94,7 @@ public function testShouldCallCalculateJobRootStatusAndACKMessage()
->expects($this->once())
->method('findJobById')
->with('12345')
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$logger = $this->createLoggerMock();
@@ -146,7 +137,7 @@ public function testShouldSendRootJobStoppedMessageIfJobHasStopped()
->expects($this->once())
->method('findJobById')
->with('12345')
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$logger = $this->createLoggerMock();
@@ -156,7 +147,7 @@ public function testShouldSendRootJobStoppedMessageIfJobHasStopped()
->expects($this->once())
->method('calculate')
->with($this->identicalTo($job))
- ->will($this->returnValue(true))
+ ->willReturn(true)
;
$producer = $this->createProducerMock();
@@ -176,7 +167,7 @@ public function testShouldSendRootJobStoppedMessageIfJobHasStopped()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ProducerInterface
+ * @return MockObject|ProducerInterface
*/
private function createProducerMock()
{
@@ -184,7 +175,7 @@ private function createProducerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Context
+ * @return MockObject|Context
*/
private function createContextMock()
{
@@ -192,7 +183,7 @@ private function createContextMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|LoggerInterface
+ * @return MockObject|LoggerInterface
*/
private function createLoggerMock()
{
@@ -200,7 +191,7 @@ private function createLoggerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|CalculateRootJobStatusService
+ * @return MockObject|CalculateRootJobStatusService
*/
private function createCalculateRootJobStatusCaseMock()
{
@@ -208,7 +199,7 @@ private function createCalculateRootJobStatusCaseMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|JobStorage
+ * @return MockObject|JobStorage
*/
private function createJobStorageMock()
{
diff --git a/pkg/job-queue/Tests/CalculateRootJobStatusServiceTest.php b/pkg/job-queue/Tests/CalculateRootJobStatusServiceTest.php
index 01f0d10ce..a0f1b4c86 100644
--- a/pkg/job-queue/Tests/CalculateRootJobStatusServiceTest.php
+++ b/pkg/job-queue/Tests/CalculateRootJobStatusServiceTest.php
@@ -5,14 +5,10 @@
use Enqueue\JobQueue\CalculateRootJobStatusService;
use Enqueue\JobQueue\Doctrine\JobStorage;
use Enqueue\JobQueue\Job;
+use PHPUnit\Framework\MockObject\MockObject;
class CalculateRootJobStatusServiceTest extends \PHPUnit\Framework\TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new CalculateRootJobStatusService($this->createJobStorageMock());
- }
-
public function stopStatusProvider()
{
return [
@@ -24,8 +20,6 @@ public function stopStatusProvider()
/**
* @dataProvider stopStatusProvider
- *
- * @param mixed $status
*/
public function testShouldDoNothingIfRootJobHasStopState($status)
{
@@ -60,9 +54,9 @@ public function testShouldCalculateRootJobStatus()
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$case = new CalculateRootJobStatusService($storage);
@@ -74,8 +68,6 @@ public function testShouldCalculateRootJobStatus()
/**
* @dataProvider stopStatusProvider
- *
- * @param mixed $stopStatus
*/
public function testShouldCalculateRootJobStatusAndSetStoppedAtTimeIfGotStopStatus($stopStatus)
{
@@ -92,16 +84,19 @@ public function testShouldCalculateRootJobStatusAndSetStoppedAtTimeIfGotStopStat
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$case = new CalculateRootJobStatusService($storage);
$case->calculate($childJob);
$this->assertEquals($stopStatus, $rootJob->getStatus());
- $this->assertEquals(new \DateTime(), $rootJob->getStoppedAt(), '', 1);
+ $this->assertEquals(
+ (new \DateTime())->getTimestamp(),
+ $rootJob->getStoppedAt()->getTimestamp()
+ );
}
public function testShouldSetStoppedAtOnlyIfWasNotSet()
@@ -120,15 +115,18 @@ public function testShouldSetStoppedAtOnlyIfWasNotSet()
$em
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$case = new CalculateRootJobStatusService($em);
$case->calculate($childJob);
- $this->assertEquals(new \DateTime('2012-12-12 12:12:12'), $rootJob->getStoppedAt());
+ $this->assertEquals(
+ (new \DateTime('2012-12-12 12:12:12'))->getTimestamp(),
+ $rootJob->getStoppedAt()->getTimestamp()
+ );
}
public function testShouldThrowIfInvalidStatus()
@@ -146,17 +144,15 @@ public function testShouldThrowIfInvalidStatus()
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$case = new CalculateRootJobStatusService($storage);
- $this->setExpectedException(
- \LogicException::class,
- 'Got unsupported job status: id: "12345" status: "invalid-status"'
- );
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Got unsupported job status: id: "12345" status: "invalid-status"');
$case->calculate($childJob);
}
@@ -179,9 +175,9 @@ public function testShouldSetStatusNewIfAllChildAreNew()
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$case = new CalculateRootJobStatusService($storage);
@@ -212,9 +208,9 @@ public function testShouldSetStatusRunningIfAnyOneIsRunning()
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$case = new CalculateRootJobStatusService($storage);
@@ -245,9 +241,9 @@ public function testShouldSetStatusRunningIfThereIsNoRunningButNewAndAnyOfStopSt
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$case = new CalculateRootJobStatusService($storage);
@@ -278,9 +274,9 @@ public function testShouldSetStatusCancelledIfAllIsStopButOneIsCancelled()
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$case = new CalculateRootJobStatusService($storage);
@@ -311,9 +307,9 @@ public function testShouldSetStatusFailedIfThereIsAnyOneIsFailedButIsNotCancelle
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$case = new CalculateRootJobStatusService($storage);
@@ -344,9 +340,9 @@ public function testShouldSetStatusSuccessIfAllAreSuccess()
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$case = new CalculateRootJobStatusService($storage);
@@ -356,7 +352,7 @@ public function testShouldSetStatusSuccessIfAllAreSuccess()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|\Enqueue\JobQueue\Doctrine\JobStorage
+ * @return MockObject|JobStorage
*/
private function createJobStorageMock()
{
diff --git a/pkg/job-queue/Tests/DependentJobContextTest.php b/pkg/job-queue/Tests/DependentJobContextTest.php
index 32340d687..35942a974 100644
--- a/pkg/job-queue/Tests/DependentJobContextTest.php
+++ b/pkg/job-queue/Tests/DependentJobContextTest.php
@@ -7,11 +7,6 @@
class DependentJobContextTest extends \PHPUnit\Framework\TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new DependentJobContext(new Job());
- }
-
public function testShouldReturnJob()
{
$job = new Job();
diff --git a/pkg/job-queue/Tests/DependentJobProcessorTest.php b/pkg/job-queue/Tests/DependentJobProcessorTest.php
index 6ae4163f1..dcebf0d49 100644
--- a/pkg/job-queue/Tests/DependentJobProcessorTest.php
+++ b/pkg/job-queue/Tests/DependentJobProcessorTest.php
@@ -11,6 +11,7 @@
use Enqueue\JobQueue\Topics;
use Enqueue\Null\NullMessage;
use Interop\Queue\Context;
+use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
class DependentJobProcessorTest extends \PHPUnit\Framework\TestCase
@@ -84,7 +85,7 @@ public function testShouldLogCriticalAndRejectMessageIfJobIsNotRoot()
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$producer = $this->createProducerMock();
@@ -115,7 +116,7 @@ public function testShouldDoNothingIfDependentJobsAreMissing()
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$producer = $this->createProducerMock();
@@ -151,7 +152,7 @@ public function testShouldLogCriticalAndRejectMessageIfDependentJobTopicIsMissin
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$producer = $this->createProducerMock();
@@ -194,7 +195,7 @@ public function testShouldLogCriticalAndRejectMessageIfDependentJobMessageIsMiss
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$producer = $this->createProducerMock();
@@ -239,7 +240,7 @@ public function testShouldPublishDependentMessage()
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$expectedMessage = null;
@@ -248,9 +249,9 @@ public function testShouldPublishDependentMessage()
->expects($this->once())
->method('sendEvent')
->with('topic-name', $this->isInstanceOf(Message::class))
- ->will($this->returnCallback(function ($topic, Message $message) use (&$expectedMessage) {
+ ->willReturnCallback(function ($topic, Message $message) use (&$expectedMessage) {
$expectedMessage = $message;
- }))
+ })
;
$logger = $this->createLoggerMock();
@@ -287,7 +288,7 @@ public function testShouldPublishDependentMessageWithPriority()
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$expectedMessage = null;
@@ -296,9 +297,9 @@ public function testShouldPublishDependentMessageWithPriority()
->expects($this->once())
->method('sendEvent')
->with('topic-name', $this->isInstanceOf(Message::class))
- ->will($this->returnCallback(function ($topic, Message $message) use (&$expectedMessage) {
+ ->willReturnCallback(function ($topic, Message $message) use (&$expectedMessage) {
$expectedMessage = $message;
- }))
+ })
;
$logger = $this->createLoggerMock();
@@ -317,7 +318,7 @@ public function testShouldPublishDependentMessageWithPriority()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Context
+ * @return MockObject|Context
*/
private function createContextMock()
{
@@ -325,7 +326,7 @@ private function createContextMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|\Enqueue\JobQueue\Doctrine\JobStorage
+ * @return MockObject|JobStorage
*/
private function createJobStorageMock()
{
@@ -333,7 +334,7 @@ private function createJobStorageMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ProducerInterface
+ * @return MockObject|ProducerInterface
*/
private function createProducerMock()
{
@@ -341,7 +342,7 @@ private function createProducerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|LoggerInterface
+ * @return MockObject|LoggerInterface
*/
private function createLoggerMock()
{
diff --git a/pkg/job-queue/Tests/DependentJobServiceTest.php b/pkg/job-queue/Tests/DependentJobServiceTest.php
index 7469b9fb8..c2a1c7b1a 100644
--- a/pkg/job-queue/Tests/DependentJobServiceTest.php
+++ b/pkg/job-queue/Tests/DependentJobServiceTest.php
@@ -6,14 +6,10 @@
use Enqueue\JobQueue\DependentJobService;
use Enqueue\JobQueue\Doctrine\JobStorage;
use Enqueue\JobQueue\Job;
+use PHPUnit\Framework\MockObject\MockObject;
class DependentJobServiceTest extends \PHPUnit\Framework\TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new DependentJobService($this->createJobStorageMock());
- }
-
public function testShouldThrowIfJobIsNotRootJob()
{
$job = new Job();
@@ -24,7 +20,8 @@ public function testShouldThrowIfJobIsNotRootJob()
$service = new DependentJobService($this->createJobStorageMock());
- $this->setExpectedException(\LogicException::class, 'Only root jobs allowed but got child. jobId: "12345"');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Only root jobs allowed but got child. jobId: "12345"');
$service->saveDependentJob($context);
}
@@ -38,11 +35,11 @@ public function testShouldSaveDependentJobs()
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
return true;
- }))
+ })
;
$context = new DependentJobContext($job);
@@ -66,7 +63,7 @@ public function testShouldSaveDependentJobs()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|\Enqueue\JobQueue\Doctrine\JobStorage
+ * @return MockObject|JobStorage
*/
private function createJobStorageMock()
{
diff --git a/pkg/job-queue/Tests/Doctrine/JobStorageTest.php b/pkg/job-queue/Tests/Doctrine/JobStorageTest.php
index 87d5a50c7..e86d0d601 100644
--- a/pkg/job-queue/Tests/Doctrine/JobStorageTest.php
+++ b/pkg/job-queue/Tests/Doctrine/JobStorageTest.php
@@ -2,30 +2,66 @@
namespace Enqueue\JobQueue\Tests\Doctrine;
-use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\DBAL\LockMode;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
+use Doctrine\Persistence\ManagerRegistry;
use Enqueue\JobQueue\Doctrine\JobStorage;
use Enqueue\JobQueue\DuplicateJobException;
use Enqueue\JobQueue\Job;
+use PHPUnit\Framework\MockObject\MockObject;
class JobStorageTest extends \PHPUnit\Framework\TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
+ public function testShouldCreateJobObject()
{
- new JobStorage($this->createDoctrineMock(), 'entity-class', 'unique_table');
+ $repository = $this->createRepositoryMock();
+ $repository
+ ->expects($this->once())
+ ->method('getClassName')
+ ->willReturn(Job::class)
+ ;
+
+ $em = $this->createEntityManagerMock();
+ $em
+ ->expects($this->once())
+ ->method('getRepository')
+ ->with('entity-class')
+ ->willReturn($repository)
+ ;
+ $em
+ ->expects($this->any())
+ ->method('isOpen')
+ ->willReturn(true)
+ ;
+
+ $doctrine = $this->createDoctrineMock();
+ $doctrine
+ ->expects($this->once())
+ ->method('getManagerForClass')
+ ->with('entity-class')
+ ->willReturn($em)
+ ;
+ $doctrine
+ ->expects($this->never())
+ ->method('resetManager')
+ ;
+
+ $storage = new JobStorage($doctrine, 'entity-class', 'unique_table');
+ $job = $storage->createJob();
+
+ $this->assertInstanceOf(Job::class, $job);
}
- public function testShouldCreateJobObject()
+ public function testShouldResetManagerAndCreateJobObject()
{
$repository = $this->createRepositoryMock();
$repository
->expects($this->once())
->method('getClassName')
- ->will($this->returnValue(Job::class))
+ ->willReturn(Job::class)
;
$em = $this->createEntityManagerMock();
@@ -33,7 +69,12 @@ public function testShouldCreateJobObject()
->expects($this->once())
->method('getRepository')
->with('entity-class')
- ->will($this->returnValue($repository))
+ ->willReturn($repository)
+ ;
+ $em
+ ->expects($this->any())
+ ->method('isOpen')
+ ->willReturn(false)
;
$doctrine = $this->createDoctrineMock();
@@ -41,7 +82,12 @@ public function testShouldCreateJobObject()
->expects($this->once())
->method('getManagerForClass')
->with('entity-class')
- ->will($this->returnValue($em))
+ ->willReturn($em)
+ ;
+ $doctrine
+ ->expects($this->any())
+ ->method('resetManager')
+ ->willReturn($em)
;
$storage = new JobStorage($doctrine, 'entity-class', 'unique_table');
@@ -56,7 +102,7 @@ public function testShouldThrowIfGotUnexpectedJobInstance()
$repository
->expects($this->once())
->method('getClassName')
- ->will($this->returnValue('expected\class\name'))
+ ->willReturn('expected\class\name')
;
$em = $this->createEntityManagerMock();
@@ -64,7 +110,12 @@ public function testShouldThrowIfGotUnexpectedJobInstance()
->expects($this->once())
->method('getRepository')
->with('entity-class')
- ->will($this->returnValue($repository))
+ ->willReturn($repository)
+ ;
+ $em
+ ->expects($this->any())
+ ->method('isOpen')
+ ->willReturn(true)
;
$doctrine = $this->createDoctrineMock();
@@ -72,16 +123,17 @@ public function testShouldThrowIfGotUnexpectedJobInstance()
->expects($this->once())
->method('getManagerForClass')
->with('entity-class')
- ->will($this->returnValue($em))
+ ->willReturn($em)
+ ;
+ $doctrine
+ ->expects($this->never())
+ ->method('resetManager')
;
$storage = new JobStorage($doctrine, 'entity-class', 'unique_table');
- $this->setExpectedException(
- \LogicException::class,
- 'Got unexpected job instance: expected: "expected\class\name", '.
- 'actual" "Enqueue\JobQueue\Job"'
- );
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Got unexpected job instance: expected: "expected\class\name", actual" "Enqueue\JobQueue\Job"');
$storage->saveJob(new Job());
}
@@ -97,7 +149,7 @@ public function testShouldSaveJobWithoutLockIfThereIsNoCallbackAndChildJob()
$repository
->expects($this->once())
->method('getClassName')
- ->will($this->returnValue(Job::class))
+ ->willReturn(Job::class)
;
$em = $this->createEntityManagerMock();
@@ -105,7 +157,7 @@ public function testShouldSaveJobWithoutLockIfThereIsNoCallbackAndChildJob()
->expects($this->once())
->method('getRepository')
->with('entity-class')
- ->will($this->returnValue($repository))
+ ->willReturn($repository)
;
$em
->expects($this->once())
@@ -118,7 +170,12 @@ public function testShouldSaveJobWithoutLockIfThereIsNoCallbackAndChildJob()
;
$em
->expects($this->never())
- ->method('transactional')
+ ->method('wrapInTransaction')
+ ;
+ $em
+ ->expects($this->any())
+ ->method('isOpen')
+ ->willReturn(true)
;
$doctrine = $this->createDoctrineMock();
@@ -126,7 +183,11 @@ public function testShouldSaveJobWithoutLockIfThereIsNoCallbackAndChildJob()
->expects($this->once())
->method('getManagerForClass')
->with('entity-class')
- ->will($this->returnValue($em))
+ ->willReturn($em)
+ ;
+ $doctrine
+ ->expects($this->never())
+ ->method('resetManager')
;
$storage = new JobStorage($doctrine, 'entity-class', 'unique_table');
@@ -142,7 +203,7 @@ public function testShouldSaveJobWithLockIfWithCallback()
$repository
->expects($this->once())
->method('getClassName')
- ->will($this->returnValue(Job::class))
+ ->willReturn(Job::class)
;
$em = $this->createEntityManagerMock();
@@ -150,7 +211,7 @@ public function testShouldSaveJobWithLockIfWithCallback()
->expects($this->once())
->method('getRepository')
->with('entity-class')
- ->will($this->returnValue($repository))
+ ->willReturn($repository)
;
$em
->expects($this->never())
@@ -163,7 +224,12 @@ public function testShouldSaveJobWithLockIfWithCallback()
;
$em
->expects($this->once())
- ->method('transactional')
+ ->method('wrapInTransaction')
+ ;
+ $em
+ ->expects($this->any())
+ ->method('isOpen')
+ ->willReturn(true)
;
$doctrine = $this->createDoctrineMock();
@@ -171,7 +237,11 @@ public function testShouldSaveJobWithLockIfWithCallback()
->expects($this->once())
->method('getManagerForClass')
->with('entity-class')
- ->will($this->returnValue($em))
+ ->willReturn($em)
+ ;
+ $doctrine
+ ->expects($this->never())
+ ->method('resetManager')
;
$storage = new JobStorage($doctrine, 'entity-class', 'unique_table');
@@ -190,16 +260,16 @@ public function testShouldCatchUniqueConstraintViolationExceptionAndThrowDuplica
$repository
->expects($this->once())
->method('getClassName')
- ->will($this->returnValue(Job::class))
+ ->willReturn(Job::class)
;
$connection = $this->createConnectionMock();
$connection
->expects($this->once())
->method('transactional')
- ->will($this->returnCallback(function ($callback) use ($connection) {
+ ->willReturnCallback(function ($callback) use ($connection) {
$callback($connection);
- }))
+ })
;
$connection
->expects($this->once())
@@ -212,12 +282,17 @@ public function testShouldCatchUniqueConstraintViolationExceptionAndThrowDuplica
->expects($this->once())
->method('getRepository')
->with('entity-class')
- ->will($this->returnValue($repository))
+ ->willReturn($repository)
;
$em
->expects($this->once())
->method('getConnection')
- ->will($this->returnValue($connection))
+ ->willReturn($connection)
+ ;
+ $em
+ ->expects($this->any())
+ ->method('isOpen')
+ ->willReturn(true)
;
$doctrine = $this->createDoctrineMock();
@@ -225,12 +300,17 @@ public function testShouldCatchUniqueConstraintViolationExceptionAndThrowDuplica
->expects($this->once())
->method('getManagerForClass')
->with('entity-class')
- ->will($this->returnValue($em))
+ ->willReturn($em)
+ ;
+ $doctrine
+ ->expects($this->never())
+ ->method('resetManager')
;
$storage = new JobStorage($doctrine, 'entity-class', 'unique_table');
- $this->setExpectedException(DuplicateJobException::class, 'Duplicate job. ownerId:"owner-id", name:"job-name"');
+ $this->expectException(DuplicateJobException::class);
+ $this->expectExceptionMessage('Duplicate job. ownerId:"owner-id", name:"job-name"');
$storage->saveJob($job);
}
@@ -243,7 +323,7 @@ public function testShouldThrowIfTryToSaveNewEntityWithLock()
$repository
->expects($this->once())
->method('getClassName')
- ->will($this->returnValue(Job::class))
+ ->willReturn(Job::class)
;
$em = $this->createEntityManagerMock();
@@ -251,7 +331,12 @@ public function testShouldThrowIfTryToSaveNewEntityWithLock()
->expects($this->once())
->method('getRepository')
->with('entity-class')
- ->will($this->returnValue($repository))
+ ->willReturn($repository)
+ ;
+ $em
+ ->expects($this->any())
+ ->method('isOpen')
+ ->willReturn(true)
;
$doctrine = $this->createDoctrineMock();
@@ -259,16 +344,17 @@ public function testShouldThrowIfTryToSaveNewEntityWithLock()
->expects($this->once())
->method('getManagerForClass')
->with('entity-class')
- ->will($this->returnValue($em))
+ ->willReturn($em)
+ ;
+ $doctrine
+ ->expects($this->never())
+ ->method('resetManager')
;
$storage = new JobStorage($doctrine, 'entity-class', 'unique_table');
- $this->setExpectedException(
- \LogicException::class,
- 'Is not possible to create new job with lock, only update is allowed'
- );
-
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Is not possible to create new job with lock, only update is allowed');
$storage->saveJob($job, function () {
});
}
@@ -283,13 +369,13 @@ public function testShouldLockEntityAndPassNewInstanceIntoCallback()
$repository
->expects($this->once())
->method('getClassName')
- ->will($this->returnValue(Job::class))
+ ->willReturn(Job::class)
;
$repository
->expects($this->once())
->method('find')
->with(12345, LockMode::PESSIMISTIC_WRITE)
- ->will($this->returnValue($lockedJob))
+ ->willReturn($lockedJob)
;
$em = $this->createEntityManagerMock();
@@ -297,14 +383,19 @@ public function testShouldLockEntityAndPassNewInstanceIntoCallback()
->expects($this->once())
->method('getRepository')
->with('entity-class')
- ->will($this->returnValue($repository))
+ ->willReturn($repository)
;
$em
->expects($this->once())
- ->method('transactional')
- ->will($this->returnCallback(function ($callback) use ($em) {
+ ->method('wrapInTransaction')
+ ->willReturnCallback(function ($callback) use ($em) {
$callback($em);
- }))
+ })
+ ;
+ $em
+ ->expects($this->any())
+ ->method('isOpen')
+ ->willReturn(true)
;
$doctrine = $this->createDoctrineMock();
@@ -312,7 +403,11 @@ public function testShouldLockEntityAndPassNewInstanceIntoCallback()
->expects($this->once())
->method('getManagerForClass')
->with('entity-class')
- ->will($this->returnValue($em))
+ ->willReturn($em)
+ ;
+ $doctrine
+ ->expects($this->never())
+ ->method('resetManager')
;
$storage = new JobStorage($doctrine, 'entity-class', 'unique_table');
@@ -335,9 +430,9 @@ public function testShouldInsertIntoUniqueTableIfJobIsUniqueAndNew()
$connection
->expects($this->once())
->method('transactional')
- ->will($this->returnCallback(function ($callback) use ($connection) {
+ ->willReturnCallback(function ($callback) use ($connection) {
$callback($connection);
- }))
+ })
;
$connection
->expects($this->at(0))
@@ -354,7 +449,7 @@ public function testShouldInsertIntoUniqueTableIfJobIsUniqueAndNew()
$repository
->expects($this->once())
->method('getClassName')
- ->will($this->returnValue(Job::class))
+ ->willReturn(Job::class)
;
$em = $this->createEntityManagerMock();
@@ -362,12 +457,12 @@ public function testShouldInsertIntoUniqueTableIfJobIsUniqueAndNew()
->expects($this->once())
->method('getRepository')
->with('entity-class')
- ->will($this->returnValue($repository))
+ ->willReturn($repository)
;
$em
->expects($this->once())
->method('getConnection')
- ->will($this->returnValue($connection))
+ ->willReturn($connection)
;
$em
->expects($this->once())
@@ -377,13 +472,22 @@ public function testShouldInsertIntoUniqueTableIfJobIsUniqueAndNew()
->expects($this->once())
->method('flush')
;
+ $em
+ ->expects($this->any())
+ ->method('isOpen')
+ ->willReturn(true)
+ ;
$doctrine = $this->createDoctrineMock();
$doctrine
->expects($this->once())
->method('getManagerForClass')
->with('entity-class')
- ->will($this->returnValue($em))
+ ->willReturn($em)
+ ;
+ $doctrine
+ ->expects($this->never())
+ ->method('resetManager')
;
$storage = new JobStorage($doctrine, 'entity-class', 'unique_table');
@@ -415,12 +519,12 @@ public function testShouldDeleteRecordFromUniqueTableIfJobIsUniqueAndStoppedAtIs
$repository
->expects($this->once())
->method('getClassName')
- ->will($this->returnValue(Job::class))
+ ->willReturn(Job::class)
;
$repository
->expects($this->once())
->method('find')
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$em = $this->createEntityManagerMock();
@@ -428,19 +532,24 @@ public function testShouldDeleteRecordFromUniqueTableIfJobIsUniqueAndStoppedAtIs
->expects($this->once())
->method('getRepository')
->with('entity-class')
- ->will($this->returnValue($repository))
+ ->willReturn($repository)
;
$em
->expects($this->once())
- ->method('transactional')
- ->will($this->returnCallback(function ($callback) use ($em) {
+ ->method('wrapInTransaction')
+ ->willReturnCallback(function ($callback) use ($em) {
$callback($em);
- }))
+ })
;
$em
->expects($this->exactly(2))
->method('getConnection')
- ->will($this->returnValue($connection))
+ ->willReturn($connection)
+ ;
+ $em
+ ->expects($this->any())
+ ->method('isOpen')
+ ->willReturn(true)
;
$doctrine = $this->createDoctrineMock();
@@ -448,7 +557,11 @@ public function testShouldDeleteRecordFromUniqueTableIfJobIsUniqueAndStoppedAtIs
->expects($this->once())
->method('getManagerForClass')
->with('entity-class')
- ->will($this->returnValue($em))
+ ->willReturn($em)
+ ;
+ $doctrine
+ ->expects($this->never())
+ ->method('resetManager')
;
$storage = new JobStorage($doctrine, 'entity-class', 'unique_table');
@@ -457,7 +570,7 @@ public function testShouldDeleteRecordFromUniqueTableIfJobIsUniqueAndStoppedAtIs
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ManagerRegistry
+ * @return MockObject|ManagerRegistry
*/
private function createDoctrineMock()
{
@@ -465,7 +578,7 @@ private function createDoctrineMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Connection
+ * @return MockObject|Connection
*/
private function createConnectionMock()
{
@@ -473,7 +586,7 @@ private function createConnectionMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|EntityManager
+ * @return MockObject|EntityManager
*/
private function createEntityManagerMock()
{
@@ -481,7 +594,7 @@ private function createEntityManagerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|EntityRepository
+ * @return MockObject|EntityRepository
*/
private function createRepositoryMock()
{
@@ -489,7 +602,7 @@ private function createRepositoryMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|UniqueConstraintViolationException
+ * @return MockObject|UniqueConstraintViolationException
*/
private function createUniqueConstraintViolationExceptionMock()
{
diff --git a/pkg/job-queue/Tests/Functional/Entity/Job.php b/pkg/job-queue/Tests/Functional/Entity/Job.php
index b6e0308a4..ad90e58a0 100644
--- a/pkg/job-queue/Tests/Functional/Entity/Job.php
+++ b/pkg/job-queue/Tests/Functional/Entity/Job.php
@@ -6,97 +6,47 @@
use Doctrine\ORM\Mapping as ORM;
use Enqueue\JobQueue\Job as BaseJob;
-/**
- * @ORM\Entity
- * @ORM\Table(name="enqueue_job_queue")
- */
+#[ORM\Entity]
+#[ORM\Table(name: 'enqueue_job_queue')]
class Job extends BaseJob
{
- /**
- * @var int
- *
- * @ORM\Column(name="id", type="integer")
- * @ORM\Id
- * @ORM\GeneratedValue(strategy="AUTO")
- */
+ #[ORM\Column(name: 'id', type: 'integer')]
+ #[ORM\Id]
+ #[ORM\GeneratedValue(strategy: 'AUTO')]
protected $id;
- /**
- * @var string
- *
- * @ORM\Column(name="owner_id", type="string", nullable=true)
- */
+ #[ORM\Column(name: 'owner_id', type: 'string', nullable: true)]
protected $ownerId;
- /**
- * @var string
- *
- * @ORM\Column(name="name", type="string", nullable=false)
- */
+ #[ORM\Column(name: 'name', type: 'string', nullable: false)]
protected $name;
- /**
- * @var string
- *
- * @ORM\Column(name="status", type="string", nullable=false)
- */
+ #[ORM\Column(name: 'status', type: 'string', nullable: false)]
protected $status;
- /**
- * @var bool
- *
- * @ORM\Column(name="interrupted", type="boolean")
- */
+ #[ORM\Column(name: 'interrupted', type: 'boolean')]
protected $interrupted;
- /**
- * @var bool;
- *
- * @ORM\Column(name="`unique`", type="boolean")
- */
+ #[ORM\Column(name: '`unique`', type: 'boolean')]
protected $unique;
- /**
- * @var Job
- *
- * @ORM\ManyToOne(targetEntity="Job", inversedBy="childJobs")
- * @ORM\JoinColumn(name="root_job_id", referencedColumnName="id", onDelete="CASCADE")
- */
+ #[ORM\ManyToOne(targetEntity: 'Job', inversedBy: 'childJobs')]
+ #[ORM\JoinColumn(name: 'root_job_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
protected $rootJob;
- /**
- * @var Job[]
- *
- * @ORM\OneToMany(targetEntity="Job", mappedBy="rootJob")
- */
+ #[ORM\OneToMany(mappedBy: 'rootJob', targetEntity: 'Job')]
protected $childJobs;
- /**
- * @var \DateTime
- *
- * @ORM\Column(name="created_at", type="datetime", nullable=false)
- */
+ #[ORM\Column(name: 'created_at', type: 'datetime', nullable: false)]
protected $createdAt;
- /**
- * @var \DateTime
- *
- * @ORM\Column(name="started_at", type="datetime", nullable=true)
- */
+ #[ORM\Column(name: 'started_at', type: 'datetime', nullable: true)]
protected $startedAt;
- /**
- * @var \DateTime
- *
- * @ORM\Column(name="stopped_at", type="datetime", nullable=true)
- */
+ #[ORM\Column(name: 'stopped_at', type: 'datetime', nullable: true)]
protected $stoppedAt;
- /**
- * @var array
- *
- * @ORM\Column(name="data", type="json_array", nullable=true)
- */
+ #[ORM\Column(name: 'data', type: 'json', nullable: true)]
protected $data;
public function __construct()
diff --git a/pkg/job-queue/Tests/Functional/Entity/JobUnique.php b/pkg/job-queue/Tests/Functional/Entity/JobUnique.php
index 4d8a33745..6d10ea2a5 100644
--- a/pkg/job-queue/Tests/Functional/Entity/JobUnique.php
+++ b/pkg/job-queue/Tests/Functional/Entity/JobUnique.php
@@ -4,15 +4,11 @@
use Doctrine\ORM\Mapping as ORM;
-/**
- * @ORM\Entity
- * @ORM\Table(name="enqueue_job_queue_unique")
- */
+#[ORM\Entity]
+#[ORM\Table(name: 'enqueue_job_queue_unique')]
class JobUnique
{
- /**
- * @ORM\Id
- * @ORM\Column(name="name", type="string", nullable=false)
- */
+ #[ORM\Id]
+ #[ORM\Column(name: 'name', type: 'string', nullable: false)]
protected $name;
}
diff --git a/pkg/job-queue/Tests/Functional/Job/JobStorageTest.php b/pkg/job-queue/Tests/Functional/Job/JobStorageTest.php
index 4cc05f8e0..e884c31e8 100644
--- a/pkg/job-queue/Tests/Functional/Job/JobStorageTest.php
+++ b/pkg/job-queue/Tests/Functional/Job/JobStorageTest.php
@@ -128,7 +128,7 @@ public function testShouldThrowIfDuplicateJob()
$job2->setStatus(Job::STATUS_NEW);
$job2->setCreatedAt(new \DateTime());
- $this->setExpectedException(DuplicateJobException::class);
+ $this->expectException(DuplicateJobException::class);
$this->getJobStorage()->saveJob($job2);
}
@@ -142,7 +142,7 @@ private function getEntityManager()
}
/**
- * @return \Enqueue\JobQueue\Doctrine\JobStorage
+ * @return JobStorage
*/
private function getJobStorage()
{
diff --git a/pkg/job-queue/Tests/Functional/WebTestCase.php b/pkg/job-queue/Tests/Functional/WebTestCase.php
index 329762004..781bb5da4 100644
--- a/pkg/job-queue/Tests/Functional/WebTestCase.php
+++ b/pkg/job-queue/Tests/Functional/WebTestCase.php
@@ -11,20 +11,20 @@ abstract class WebTestCase extends BaseWebTestCase
/**
* @var Client
*/
- protected $client;
+ protected static $client;
/**
* @var ContainerInterface
*/
protected static $container;
- protected function setUp()
+ protected function setUp(): void
{
parent::setUp();
static::$class = null;
- $this->client = static::createClient();
+ static::$client = static::createClient();
if (false == static::$container) {
static::$container = static::$kernel->getContainer();
@@ -33,17 +33,14 @@ protected function setUp()
$this->startTransaction();
}
- protected function tearDown()
+ protected function tearDown(): void
{
$this->rollbackTransaction();
-
parent::tearDown();
+ static::ensureKernelShutdown();
}
- /**
- * @return string
- */
- public static function getKernelClass()
+ public static function getKernelClass(): string
{
require_once __DIR__.'/app/AppKernel.php';
@@ -61,9 +58,9 @@ protected function startTransaction()
protected function rollbackTransaction()
{
- //the error can be thrown during setUp
- //It would be caught by phpunit and tearDown called.
- //In this case we could not rollback since container may not exist.
+ // the error can be thrown during setUp
+ // It would be caught by phpunit and tearDown called.
+ // In this case we could not rollback since container may not exist.
if (false == static::$container) {
return;
}
diff --git a/pkg/job-queue/Tests/Functional/app/AppKernel.php b/pkg/job-queue/Tests/Functional/app/AppKernel.php
index ce21df0b8..fe31ceb86 100644
--- a/pkg/job-queue/Tests/Functional/app/AppKernel.php
+++ b/pkg/job-queue/Tests/Functional/app/AppKernel.php
@@ -1,50 +1,36 @@
load(__DIR__.'/config/config.yml');
}
- protected function getContainerClass()
+ protected function getContainerClass(): string
{
return parent::getContainerClass().'JobQueue';
}
diff --git a/pkg/job-queue/Tests/Functional/app/config/config.yml b/pkg/job-queue/Tests/Functional/app/config/config.yml
index 2297c7bb4..578a21df9 100644
--- a/pkg/job-queue/Tests/Functional/app/config/config.yml
+++ b/pkg/job-queue/Tests/Functional/app/config/config.yml
@@ -7,11 +7,10 @@ framework:
#translator: { fallback: "%locale%" }
test: ~
assets: false
- templating: false
session:
- storage_id: session.storage.mock_file
+ storage_factory_id: session.storage.factory.mock_file
secret: "%secret%"
- router: { resource: "%kernel.root_dir%/config/routing.yml" }
+ router: { resource: "%kernel.project_dir%/config/routing.yml" }
default_locale: "%locale%"
doctrine:
@@ -21,13 +20,12 @@ doctrine:
charset: UTF8
wrapper_class: "Enqueue\\JobQueue\\Test\\DbalPersistedConnection"
orm:
- auto_generate_proxy_classes: true
auto_mapping: true
mappings:
TestEntity:
mapping: true
- type: annotation
- dir: '%kernel.root_dir%/../Entity'
+ type: attribute
+ dir: '%kernel.project_dir%/Tests/Functional/Entity'
alias: 'EnqueueJobQueue'
prefix: 'Enqueue\JobQueue\Tests\Functional\Entity'
is_bundle: false
diff --git a/pkg/job-queue/Tests/JobProcessorTest.php b/pkg/job-queue/Tests/JobProcessorTest.php
index 483e8ef2d..9f1c7b2fd 100644
--- a/pkg/job-queue/Tests/JobProcessorTest.php
+++ b/pkg/job-queue/Tests/JobProcessorTest.php
@@ -8,20 +8,17 @@
use Enqueue\JobQueue\DuplicateJobException;
use Enqueue\JobQueue\Job;
use Enqueue\JobQueue\JobProcessor;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class JobProcessorTest extends TestCase
{
- public function testCouldBeCreatedWithRequiredArguments()
- {
- new JobProcessor($this->createJobStorage(), $this->createProducerMock());
- }
-
public function testCreateRootJobShouldThrowIfOwnerIdIsEmpty()
{
$processor = new JobProcessor($this->createJobStorage(), $this->createProducerMock());
- $this->setExpectedException(\LogicException::class, 'OwnerId must not be empty');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('OwnerId must not be empty');
$processor->findOrCreateRootJob(null, 'job-name', true);
}
@@ -30,7 +27,8 @@ public function testCreateRootJobShouldThrowIfNameIsEmpty()
{
$processor = new JobProcessor($this->createJobStorage(), $this->createProducerMock());
- $this->setExpectedException(\LogicException::class, 'Job name must not be empty');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Job name must not be empty');
$processor->findOrCreateRootJob('owner-id', null, true);
}
@@ -43,7 +41,7 @@ public function testShouldCreateRootJobAndReturnIt()
$storage
->expects($this->once())
->method('createJob')
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$storage
->expects($this->once())
@@ -57,8 +55,14 @@ public function testShouldCreateRootJobAndReturnIt()
$this->assertSame($job, $result);
$this->assertEquals(Job::STATUS_NEW, $job->getStatus());
- $this->assertEquals(new \DateTime(), $job->getCreatedAt(), '', 1);
- $this->assertEquals(new \DateTime(), $job->getStartedAt(), '', 1);
+ $this->assertEquals(
+ (new \DateTime())->getTimestamp(),
+ $job->getCreatedAt()->getTimestamp()
+ );
+ $this->assertEquals(
+ (new \DateTime())->getTimestamp(),
+ $job->getStartedAt()->getTimestamp()
+ );
$this->assertNull($job->getStoppedAt());
$this->assertEquals('job-name', $job->getName());
$this->assertEquals('owner-id', $job->getOwnerId());
@@ -72,7 +76,7 @@ public function testShouldCatchDuplicateJobAndTryToFindJobByOwnerId()
$storage
->expects($this->once())
->method('createJob')
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$storage
->expects($this->once())
@@ -84,7 +88,7 @@ public function testShouldCatchDuplicateJobAndTryToFindJobByOwnerId()
->expects($this->once())
->method('findRootJobByOwnerIdAndJobName')
->with('owner-id', 'job-name')
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$processor = new JobProcessor($storage, $this->createProducerMock());
@@ -98,7 +102,8 @@ public function testCreateChildJobShouldThrowIfNameIsEmpty()
{
$processor = new JobProcessor($this->createJobStorage(), $this->createProducerMock());
- $this->setExpectedException(\LogicException::class, 'Job name must not be empty');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Job name must not be empty');
$processor->findOrCreateChildJob(null, new Job());
}
@@ -121,13 +126,13 @@ public function testCreateChildJobShouldFindAndReturnAlreadyCreatedJob()
->expects($this->once())
->method('findChildJobByName')
->with('job-name', $this->identicalTo($job))
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$storage
->expects($this->once())
->method('findJobById')
->with(123)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$processor = new JobProcessor($storage, $this->createProducerMock());
@@ -146,7 +151,7 @@ public function testCreateChildJobShouldCreateAndSaveJobAndPublishRecalculateRoo
$storage
->expects($this->once())
->method('createJob')
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$storage
->expects($this->once())
@@ -157,19 +162,19 @@ public function testCreateChildJobShouldCreateAndSaveJobAndPublishRecalculateRoo
->expects($this->once())
->method('findChildJobByName')
->with('job-name', $this->identicalTo($job))
- ->will($this->returnValue(null))
+ ->willReturn(null)
;
$storage
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$producer = $this->createProducerMock();
$producer
->expects($this->once())
- ->method('sendEvent')
+ ->method('sendCommand')
->with(Commands::CALCULATE_ROOT_JOB_STATUS, ['jobId' => 12345])
;
@@ -179,7 +184,10 @@ public function testCreateChildJobShouldCreateAndSaveJobAndPublishRecalculateRoo
$this->assertSame($job, $result);
$this->assertEquals(Job::STATUS_NEW, $job->getStatus());
- $this->assertEquals(new \DateTime(), $job->getCreatedAt(), '', 1);
+ $this->assertEquals(
+ (new \DateTime())->getTimestamp(),
+ $job->getCreatedAt()->getTimestamp()
+ );
$this->assertNull($job->getStartedAt());
$this->assertNull($job->getStoppedAt());
$this->assertEquals('job-name', $job->getName());
@@ -193,7 +201,8 @@ public function testStartChildJobShouldThrowIfRootJob()
$rootJob = new Job();
$rootJob->setId(12345);
- $this->setExpectedException(\LogicException::class, 'Can\'t start root jobs. id: "12345"');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Can\'t start root jobs. id: "12345"');
$processor->startChildJob($rootJob);
}
@@ -210,15 +219,13 @@ public function testStartChildJobShouldThrowIfJobHasNotNewStatus()
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$processor = new JobProcessor($storage, $this->createProducerMock());
- $this->setExpectedException(
- \LogicException::class,
- 'Can start only new jobs: id: "12345", status: "enqueue.job_queue.status.cancelled"'
- );
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Can start only new jobs: id: "12345", status: "enqueue.job_queue.status.cancelled"');
$processor->startChildJob($job);
}
@@ -240,20 +247,23 @@ public function testStartJobShouldUpdateJobWithRunningStatusAndStartAtTime()
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$producer = $this->createProducerMock();
$producer
->expects($this->once())
- ->method('sendEvent')
+ ->method('sendCommand')
;
$processor = new JobProcessor($storage, $producer);
$processor->startChildJob($job);
$this->assertEquals(Job::STATUS_RUNNING, $job->getStatus());
- $this->assertEquals(new \DateTime(), $job->getStartedAt(), '', 1);
+ $this->assertEquals(
+ (new \DateTime())->getTimestamp(),
+ $job->getStartedAt()->getTimestamp()
+ );
}
public function testSuccessChildJobShouldThrowIfRootJob()
@@ -263,7 +273,8 @@ public function testSuccessChildJobShouldThrowIfRootJob()
$rootJob = new Job();
$rootJob->setId(12345);
- $this->setExpectedException(\LogicException::class, 'Can\'t success root jobs. id: "12345"');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Can\'t success root jobs. id: "12345"');
$processor->successChildJob($rootJob);
}
@@ -280,15 +291,13 @@ public function testSuccessChildJobShouldThrowIfJobHasNotRunningStatus()
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$processor = new JobProcessor($storage, $this->createProducerMock());
- $this->setExpectedException(
- \LogicException::class,
- 'Can success only running jobs. id: "12345", status: "enqueue.job_queue.status.cancelled"'
- );
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Can success only running jobs. id: "12345", status: "enqueue.job_queue.status.cancelled"');
$processor->successChildJob($job);
}
@@ -310,20 +319,23 @@ public function testSuccessJobShouldUpdateJobWithSuccessStatusAndStopAtTime()
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$producer = $this->createProducerMock();
$producer
->expects($this->once())
- ->method('sendEvent')
+ ->method('sendCommand')
;
$processor = new JobProcessor($storage, $producer);
$processor->successChildJob($job);
$this->assertEquals(Job::STATUS_SUCCESS, $job->getStatus());
- $this->assertEquals(new \DateTime(), $job->getStoppedAt(), '', 1);
+ $this->assertEquals(
+ (new \DateTime())->getTimestamp(),
+ $job->getStoppedAt()->getTimestamp()
+ );
}
public function testFailChildJobShouldThrowIfRootJob()
@@ -333,7 +345,8 @@ public function testFailChildJobShouldThrowIfRootJob()
$rootJob = new Job();
$rootJob->setId(12345);
- $this->setExpectedException(\LogicException::class, 'Can\'t fail root jobs. id: "12345"');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Can\'t fail root jobs. id: "12345"');
$processor->failChildJob($rootJob);
}
@@ -350,15 +363,13 @@ public function testFailChildJobShouldThrowIfJobHasNotRunningStatus()
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$processor = new JobProcessor($storage, $this->createProducerMock());
- $this->setExpectedException(
- \LogicException::class,
- 'Can fail only running jobs. id: "12345", status: "enqueue.job_queue.status.cancelled"'
- );
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Can fail only running jobs. id: "12345", status: "enqueue.job_queue.status.cancelled"');
$processor->failChildJob($job);
}
@@ -380,20 +391,23 @@ public function testFailJobShouldUpdateJobWithFailStatusAndStopAtTime()
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$producer = $this->createProducerMock();
$producer
->expects($this->once())
- ->method('sendEvent')
+ ->method('sendCommand')
;
$processor = new JobProcessor($storage, $producer);
$processor->failChildJob($job);
$this->assertEquals(Job::STATUS_FAILED, $job->getStatus());
- $this->assertEquals(new \DateTime(), $job->getStoppedAt(), '', 1);
+ $this->assertEquals(
+ (new \DateTime())->getTimestamp(),
+ $job->getStoppedAt()->getTimestamp()
+ );
}
public function testCancelChildJobShouldThrowIfRootJob()
@@ -403,7 +417,8 @@ public function testCancelChildJobShouldThrowIfRootJob()
$rootJob = new Job();
$rootJob->setId(12345);
- $this->setExpectedException(\LogicException::class, 'Can\'t cancel root jobs. id: "12345"');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Can\'t cancel root jobs. id: "12345"');
$processor->cancelChildJob($rootJob);
}
@@ -420,15 +435,13 @@ public function testCancelChildJobShouldThrowIfJobHasNotNewOrRunningStatus()
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$processor = new JobProcessor($storage, $this->createProducerMock());
- $this->setExpectedException(
- \LogicException::class,
- 'Can cancel only new or running jobs. id: "12345", status: "enqueue.job_queue.status.cancelled"'
- );
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Can cancel only new or running jobs. id: "12345", status: "enqueue.job_queue.status.cancelled"');
$processor->cancelChildJob($job);
}
@@ -450,21 +463,27 @@ public function testCancelJobShouldUpdateJobWithCancelStatusAndStoppedAtTimeAndS
->expects($this->once())
->method('findJobById')
->with(12345)
- ->will($this->returnValue($job))
+ ->willReturn($job)
;
$producer = $this->createProducerMock();
$producer
->expects($this->once())
- ->method('sendEvent')
+ ->method('sendCommand')
;
$processor = new JobProcessor($storage, $producer);
$processor->cancelChildJob($job);
$this->assertEquals(Job::STATUS_CANCELLED, $job->getStatus());
- $this->assertEquals(new \DateTime(), $job->getStoppedAt(), '', 1);
- $this->assertEquals(new \DateTime(), $job->getStartedAt(), '', 1);
+ $this->assertEquals(
+ (new \DateTime())->getTimestamp(),
+ $job->getStoppedAt()->getTimestamp()
+ );
+ $this->assertEquals(
+ (new \DateTime())->getTimestamp(),
+ $job->getStartedAt()->getTimestamp()
+ );
}
public function testInterruptRootJobShouldThrowIfNotRootJob()
@@ -475,7 +494,8 @@ public function testInterruptRootJobShouldThrowIfNotRootJob()
$processor = new JobProcessor($this->createJobStorage(), $this->createProducerMock());
- $this->setExpectedException(\LogicException::class, 'Can interrupt only root jobs. id: "123"');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Can interrupt only root jobs. id: "123"');
$processor->interruptRootJob($notRootJob);
}
@@ -505,9 +525,9 @@ public function testInterruptRootJobShouldUpdateJobAndSetInterruptedTrue()
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$processor = new JobProcessor($storage, $this->createProducerMock());
@@ -526,20 +546,23 @@ public function testInterruptRootJobShouldUpdateJobAndSetInterruptedTrueAndStopp
$storage
->expects($this->once())
->method('saveJob')
- ->will($this->returnCallback(function (Job $job, $callback) {
+ ->willReturnCallback(function (Job $job, $callback) {
$callback($job);
- }))
+ })
;
$processor = new JobProcessor($storage, $this->createProducerMock());
$processor->interruptRootJob($rootJob, true);
$this->assertTrue($rootJob->isInterrupted());
- $this->assertEquals(new \DateTime(), $rootJob->getStoppedAt(), '', 1);
+ $this->assertEquals(
+ (new \DateTime())->getTimestamp(),
+ $rootJob->getStoppedAt()->getTimestamp()
+ );
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createJobStorage(): JobStorage
{
@@ -547,7 +570,7 @@ private function createJobStorage(): JobStorage
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject
+ * @return MockObject
*/
private function createProducerMock(): ProducerInterface
{
diff --git a/pkg/job-queue/Tests/JobRunnerTest.php b/pkg/job-queue/Tests/JobRunnerTest.php
index 07961b35f..e43440fe3 100644
--- a/pkg/job-queue/Tests/JobRunnerTest.php
+++ b/pkg/job-queue/Tests/JobRunnerTest.php
@@ -6,6 +6,7 @@
use Enqueue\JobQueue\JobProcessor;
use Enqueue\JobQueue\JobRunner;
use Enqueue\JobQueue\OrphanJobException;
+use PHPUnit\Framework\MockObject\MockObject;
class JobRunnerTest extends \PHPUnit\Framework\TestCase
{
@@ -19,13 +20,13 @@ public function testRunUniqueShouldCreateRootAndChildJobAndCallCallback()
->expects($this->once())
->method('findOrCreateRootJob')
->with('owner-id', 'job-name', true)
- ->will($this->returnValue($root))
+ ->willReturn($root)
;
$jobProcessor
->expects($this->once())
->method('findOrCreateChildJob')
->with('job-name')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$expChild = null;
@@ -57,12 +58,12 @@ public function testRunUniqueShouldStartChildJobIfNotStarted()
$jobProcessor
->expects($this->once())
->method('findOrCreateRootJob')
- ->will($this->returnValue($root))
+ ->willReturn($root)
;
$jobProcessor
->expects($this->once())
->method('findOrCreateChildJob')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$jobProcessor
->expects($this->once())
@@ -85,12 +86,12 @@ public function testRunUniqueShouldNotStartChildJobIfAlreadyStarted()
$jobProcessor
->expects($this->once())
->method('findOrCreateRootJob')
- ->will($this->returnValue($root))
+ ->willReturn($root)
;
$jobProcessor
->expects($this->once())
->method('findOrCreateChildJob')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$jobProcessor
->expects($this->never())
@@ -111,12 +112,12 @@ public function testRunUniqueShouldSuccessJobIfCallbackReturnValueIsTrue()
$jobProcessor
->expects($this->once())
->method('findOrCreateRootJob')
- ->will($this->returnValue($root))
+ ->willReturn($root)
;
$jobProcessor
->expects($this->once())
->method('findOrCreateChildJob')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$jobProcessor
->expects($this->once())
@@ -142,12 +143,12 @@ public function testRunUniqueShouldFailJobIfCallbackReturnValueIsFalse()
$jobProcessor
->expects($this->once())
->method('findOrCreateRootJob')
- ->will($this->returnValue($root))
+ ->willReturn($root)
;
$jobProcessor
->expects($this->once())
->method('findOrCreateChildJob')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$jobProcessor
->expects($this->never())
@@ -173,12 +174,12 @@ public function testRunUniqueShouldFailJobIfCallbackThrowsException()
$jobProcessor
->expects($this->once())
->method('findOrCreateRootJob')
- ->will($this->returnValue($root))
+ ->willReturn($root)
;
$jobProcessor
->expects($this->once())
->method('findOrCreateChildJob')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$jobProcessor
->expects($this->never())
@@ -205,12 +206,12 @@ public function testRunUniqueShouldThrowOrphanJobExceptionIfChildCleanupFails()
$jobProcessor
->expects($this->once())
->method('findOrCreateRootJob')
- ->will($this->returnValue($root))
+ ->willReturn($root)
;
$jobProcessor
->expects($this->once())
->method('findOrCreateChildJob')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$jobProcessor
->expects($this->never())
@@ -239,12 +240,12 @@ public function testRunUniqueShouldNotSuccessJobIfJobIsAlreadyStopped()
$jobProcessor
->expects($this->once())
->method('findOrCreateRootJob')
- ->will($this->returnValue($root))
+ ->willReturn($root)
;
$jobProcessor
->expects($this->once())
->method('findOrCreateChildJob')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$jobProcessor
->expects($this->never())
@@ -271,7 +272,7 @@ public function testCreateDelayedShouldCreateChildJobAndCallCallback()
->expects($this->once())
->method('findOrCreateChildJob')
->with('job-name', $this->identicalTo($root))
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$expRunner = null;
@@ -296,12 +297,13 @@ public function testRunDelayedShouldThrowExceptionIfJobWasNotFoundById()
->expects($this->once())
->method('findJobById')
->with('job-id')
- ->will($this->returnValue(null))
+ ->willReturn(null)
;
$jobRunner = new JobRunner($jobProcessor);
- $this->setExpectedException(\LogicException::class, 'Job was not found. id: "job-id"');
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Job was not found. id: "job-id"');
$jobRunner->runDelayed('job-id', function () {
});
@@ -318,7 +320,7 @@ public function testRunDelayedShouldFindJobAndCallCallback()
->expects($this->once())
->method('findJobById')
->with('job-id')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$expRunner = null;
@@ -348,7 +350,7 @@ public function testRunDelayedShouldCancelJobIfRootJobIsInterrupted()
->expects($this->once())
->method('findJobById')
->with('job-id')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$jobProcessor
->expects($this->once())
@@ -373,7 +375,7 @@ public function testRunDelayedShouldSuccessJobIfCallbackReturnValueIsTrue()
->expects($this->once())
->method('findJobById')
->with('job-id')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$jobProcessor
->expects($this->once())
@@ -402,7 +404,7 @@ public function testRunDelayedShouldFailJobIfCallbackReturnValueIsFalse()
->expects($this->once())
->method('findJobById')
->with('job-id')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$jobProcessor
->expects($this->never())
@@ -432,7 +434,7 @@ public function testRunDelayedShouldNotSuccessJobIfAlreadyStopped()
->expects($this->once())
->method('findJobById')
->with('job-id')
- ->will($this->returnValue($child))
+ ->willReturn($child)
;
$jobProcessor
->expects($this->never())
@@ -450,7 +452,7 @@ public function testRunDelayedShouldNotSuccessJobIfAlreadyStopped()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|JobProcessor
+ * @return MockObject|JobProcessor
*/
private function createJobProcessorMock()
{
diff --git a/pkg/job-queue/Topics.php b/pkg/job-queue/Topics.php
index 61b424b25..891ea26f7 100644
--- a/pkg/job-queue/Topics.php
+++ b/pkg/job-queue/Topics.php
@@ -4,5 +4,5 @@
class Topics
{
- const ROOT_JOB_STOPPED = 'enqueue.message_queue.job.root_job_stopped';
+ public const ROOT_JOB_STOPPED = 'enqueue.message_queue.job.root_job_stopped';
}
diff --git a/pkg/job-queue/composer.json b/pkg/job-queue/composer.json
index 7ea67465e..4570694b5 100644
--- a/pkg/job-queue/composer.json
+++ b/pkg/job-queue/composer.json
@@ -6,19 +6,21 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "enqueue/enqueue": "0.9.x-dev",
- "enqueue/null": "0.9.x-dev",
- "queue-interop/queue-interop": "0.7.x-dev",
- "doctrine/orm": "~2.4"
+ "php": "^8.1",
+ "enqueue/enqueue": "^0.10",
+ "enqueue/null": "^0.10",
+ "queue-interop/queue-interop": "^0.8",
+ "doctrine/orm": "^2.12",
+ "doctrine/dbal": "^3.2|^4.0"
},
"require-dev": {
- "phpunit/phpunit": "~5.5",
- "enqueue/test": "0.9.x-dev",
- "doctrine/doctrine-bundle": "~1.2",
- "symfony/browser-kit": "^3.4|^4",
- "symfony/expression-language": "^3.4|^4",
- "symfony/framework-bundle": "^3.4|^4"
+ "phpunit/phpunit": "^9.5",
+ "enqueue/test": "0.10.x-dev",
+ "doctrine/doctrine-bundle": "^2.5|^3.1",
+ "symfony/browser-kit": "^7.0|^8.0",
+ "symfony/expression-language": "^7.0|^8.0",
+ "symfony/framework-bundle": "^7.0|^8.0",
+ "symfony/yaml": "^7.0|^8.0"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -36,7 +38,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/job-queue/phpunit.xml.dist b/pkg/job-queue/phpunit.xml.dist
index 29dc33404..3665922c4 100644
--- a/pkg/job-queue/phpunit.xml.dist
+++ b/pkg/job-queue/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/mongodb/.gitattributes b/pkg/mongodb/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/mongodb/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/mongodb/.github/workflows/ci.yml b/pkg/mongodb/.github/workflows/ci.yml
new file mode 100644
index 000000000..3bedbd6ff
--- /dev/null
+++ b/pkg/mongodb/.github/workflows/ci.yml
@@ -0,0 +1,30 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+ extensions: mongodb
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/mongodb/.travis.yml b/pkg/mongodb/.travis.yml
deleted file mode 100644
index 6415d29e8..000000000
--- a/pkg/mongodb/.travis.yml
+++ /dev/null
@@ -1,27 +0,0 @@
-sudo: false
-
-language: php
-
-php:
- - '7.1'
-
-git:
- depth: 10
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-services:
- - mongodb
-
-before_install:
- - echo "extension = mongodb.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
-
-install:
- - composer self-update
- - composer install --prefer-source
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
-
diff --git a/pkg/mongodb/JSON.php b/pkg/mongodb/JSON.php
index 84cac50da..481b7f9ff 100644
--- a/pkg/mongodb/JSON.php
+++ b/pkg/mongodb/JSON.php
@@ -14,10 +14,7 @@ class JSON
public static function decode($string)
{
if (!is_string($string)) {
- throw new \InvalidArgumentException(sprintf(
- 'Accept only string argument but got: "%s"',
- is_object($string) ? get_class($string) : gettype($string)
- ));
+ throw new \InvalidArgumentException(sprintf('Accept only string argument but got: "%s"', is_object($string) ? $string::class : gettype($string)));
}
// PHP7 fix - empty string and null cause syntax error
@@ -26,32 +23,22 @@ public static function decode($string)
}
$decoded = json_decode($string, true);
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'The malformed json given. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
}
return $decoded;
}
/**
- * @param mixed $value
- *
* @return string
*/
public static function encode($value)
{
- $encoded = json_encode($value, JSON_UNESCAPED_UNICODE);
-
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'Could not encode value into json. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ $encoded = json_encode($value, \JSON_UNESCAPED_UNICODE);
+
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('Could not encode value into json. Error %s and message %s', json_last_error(), json_last_error_msg()));
}
return $encoded;
diff --git a/pkg/mongodb/MongodbConnectionFactory.php b/pkg/mongodb/MongodbConnectionFactory.php
index 28a5fc068..3d34f7369 100644
--- a/pkg/mongodb/MongodbConnectionFactory.php
+++ b/pkg/mongodb/MongodbConnectionFactory.php
@@ -27,7 +27,7 @@ class MongodbConnectionFactory implements ConnectionFactory
*
* or
*
- * mongodb://127.0.0.1:27017/dbname?polling_interval=1000&enqueue_collection=enqueue
+ * mongodb://127.0.0.1:27017/defaultauthdb?polling_interval=1000&enqueue_database=enqueue&enqueue_collection=enqueue
*
* @param array|string|null $config
*/
@@ -38,7 +38,10 @@ public function __construct($config = 'mongodb:')
} elseif (is_string($config)) {
$config = $this->parseDsn($config);
} elseif (is_array($config)) {
- $config = $this->parseDsn(empty($config['dsn']) ? 'mongodb:' : $config['dsn']);
+ $config = array_replace(
+ $config,
+ $this->parseDsn(empty($config['dsn']) ? 'mongodb:' : $config['dsn'])
+ );
} else {
throw new \LogicException('The config must be either an array of options, a DSN string or null');
}
@@ -74,11 +77,7 @@ public static function parseDsn(string $dsn): array
'mongodb' => true,
];
if (false == isset($parsedUrl['scheme'])) {
- throw new \LogicException(sprintf(
- 'The given DSN schema "%s" is not supported. There are supported schemes: "%s".',
- $parsedUrl['scheme'],
- implode('", "', array_keys($supported))
- ));
+ throw new \LogicException(sprintf('The given DSN schema "%s" is not supported. There are supported schemes: "%s".', $parsedUrl['scheme'], implode('", "', array_keys($supported))));
}
if ('mongodb:' === $dsn) {
return [
@@ -86,9 +85,11 @@ public static function parseDsn(string $dsn): array
];
}
$config['dsn'] = $dsn;
+ // FIXME this is NOT a dbname but rather authdb. But removing this would be a BC break.
+ // see: https://github.com/php-enqueue/enqueue-dev/issues/1027
if (isset($parsedUrl['path']) && '/' !== $parsedUrl['path']) {
$pathParts = explode('/', $parsedUrl['path']);
- //DB name
+ // DB name
if ($pathParts[1]) {
$config['dbname'] = $pathParts[1];
}
@@ -96,13 +97,16 @@ public static function parseDsn(string $dsn): array
if (isset($parsedUrl['query'])) {
$queryParts = null;
parse_str($parsedUrl['query'], $queryParts);
- //get enqueue attributes values
+ // get enqueue attributes values
if (!empty($queryParts['polling_interval'])) {
- $config['polling_interval'] = $queryParts['polling_interval'];
+ $config['polling_interval'] = (int) $queryParts['polling_interval'];
}
if (!empty($queryParts['enqueue_collection'])) {
$config['collection_name'] = $queryParts['enqueue_collection'];
}
+ if (!empty($queryParts['enqueue_database'])) {
+ $config['dbname'] = $queryParts['enqueue_database'];
+ }
}
return $config;
diff --git a/pkg/mongodb/MongodbConsumer.php b/pkg/mongodb/MongodbConsumer.php
index 494210573..37ef12530 100644
--- a/pkg/mongodb/MongodbConsumer.php
+++ b/pkg/mongodb/MongodbConsumer.php
@@ -109,6 +109,7 @@ public function reject(Message $message, bool $requeue = false): void
InvalidMessageException::assertMessageInstanceOf($message, MongodbMessage::class);
if ($requeue) {
+ $message->setRedelivered(true);
$this->context->createProducer()->send($this->queue, $message);
return;
diff --git a/pkg/mongodb/MongodbContext.php b/pkg/mongodb/MongodbContext.php
index 968c98b1e..2e52ebdb2 100644
--- a/pkg/mongodb/MongodbContext.php
+++ b/pkg/mongodb/MongodbContext.php
@@ -158,7 +158,9 @@ public function getConfig(): array
public function createCollection(): void
{
$collection = $this->getCollection();
+ $collection->createIndex(['queue' => 1], ['name' => 'enqueue_queue']);
$collection->createIndex(['priority' => -1, 'published_at' => 1], ['name' => 'enqueue_priority']);
$collection->createIndex(['delayed_until' => 1], ['name' => 'enqueue_delayed']);
+ $collection->createIndex(['queue' => 1, 'priority' => -1, 'published_at' => 1, 'delayed_until' => 1], ['name' => 'enqueue_combined']);
}
}
diff --git a/pkg/mongodb/MongodbMessage.php b/pkg/mongodb/MongodbMessage.php
index fbfbd75d6..fadc5dd4e 100644
--- a/pkg/mongodb/MongodbMessage.php
+++ b/pkg/mongodb/MongodbMessage.php
@@ -65,7 +65,7 @@ public function __construct(string $body = '', array $properties = [], array $he
$this->redelivered = false;
}
- public function setId(string $id = null): void
+ public function setId(?string $id = null): void
{
$this->id = $id;
}
@@ -135,7 +135,7 @@ public function setRedelivered(bool $redelivered): void
$this->redelivered = $redelivered;
}
- public function setReplyTo(string $replyTo = null): void
+ public function setReplyTo(?string $replyTo = null): void
{
$this->setHeader('reply_to', $replyTo);
}
@@ -150,7 +150,7 @@ public function getPriority(): ?int
return $this->priority;
}
- public function setPriority(int $priority = null): void
+ public function setPriority(?int $priority = null): void
{
$this->priority = $priority;
}
@@ -163,7 +163,7 @@ public function getDeliveryDelay(): ?int
/**
* In milliseconds.
*/
- public function setDeliveryDelay(int $deliveryDelay = null): void
+ public function setDeliveryDelay(?int $deliveryDelay = null): void
{
$this->deliveryDelay = $deliveryDelay;
}
@@ -176,12 +176,12 @@ public function getTimeToLive(): ?int
/**
* In milliseconds.
*/
- public function setTimeToLive(int $timeToLive = null): void
+ public function setTimeToLive(?int $timeToLive = null): void
{
$this->timeToLive = $timeToLive;
}
- public function setCorrelationId(string $correlationId = null): void
+ public function setCorrelationId(?string $correlationId = null): void
{
$this->setHeader('correlation_id', $correlationId);
}
@@ -191,7 +191,7 @@ public function getCorrelationId(): ?string
return $this->getHeader('correlation_id', null);
}
- public function setMessageId(string $messageId = null): void
+ public function setMessageId(?string $messageId = null): void
{
$this->setHeader('message_id', $messageId);
}
@@ -208,7 +208,7 @@ public function getTimestamp(): ?int
return null === $value ? null : (int) $value;
}
- public function setTimestamp(int $timestamp = null): void
+ public function setTimestamp(?int $timestamp = null): void
{
$this->setHeader('timestamp', $timestamp);
}
@@ -221,7 +221,7 @@ public function getPublishedAt(): ?int
/**
* In milliseconds.
*/
- public function setPublishedAt(int $publishedAt = null): void
+ public function setPublishedAt(?int $publishedAt = null): void
{
$this->publishedAt = $publishedAt;
}
diff --git a/pkg/mongodb/MongodbProducer.php b/pkg/mongodb/MongodbProducer.php
index d27f014eb..ed28a6681 100644
--- a/pkg/mongodb/MongodbProducer.php
+++ b/pkg/mongodb/MongodbProducer.php
@@ -77,10 +77,7 @@ public function send(Destination $destination, Message $message): void
$delay = $message->getDeliveryDelay();
if ($delay) {
if (!is_int($delay)) {
- throw new \LogicException(sprintf(
- 'Delay must be integer but got: "%s"',
- is_object($delay) ? get_class($delay) : gettype($delay)
- ));
+ throw new \LogicException(sprintf('Delay must be integer but got: "%s"', is_object($delay) ? $delay::class : gettype($delay)));
}
if ($delay <= 0) {
@@ -93,10 +90,7 @@ public function send(Destination $destination, Message $message): void
$timeToLive = $message->getTimeToLive();
if ($timeToLive) {
if (!is_int($timeToLive)) {
- throw new \LogicException(sprintf(
- 'TimeToLive must be integer but got: "%s"',
- is_object($timeToLive) ? get_class($timeToLive) : gettype($timeToLive)
- ));
+ throw new \LogicException(sprintf('TimeToLive must be integer but got: "%s"', is_object($timeToLive) ? $timeToLive::class : gettype($timeToLive)));
}
if ($timeToLive <= 0) {
@@ -110,14 +104,14 @@ public function send(Destination $destination, Message $message): void
$collection = $this->context->getCollection();
$collection->insertOne($mongoMessage);
} catch (\Exception $e) {
- throw new Exception('The transport has failed to send the message due to some internal error.', null, $e);
+ throw new Exception('The transport has failed to send the message due to some internal error.', $e->getCode(), $e);
}
}
/**
* @return self
*/
- public function setDeliveryDelay(int $deliveryDelay = null): Producer
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
{
$this->deliveryDelay = $deliveryDelay;
@@ -132,7 +126,7 @@ public function getDeliveryDelay(): ?int
/**
* @return self
*/
- public function setPriority(int $priority = null): Producer
+ public function setPriority(?int $priority = null): Producer
{
$this->priority = $priority;
@@ -147,7 +141,7 @@ public function getPriority(): ?int
/**
* @return self
*/
- public function setTimeToLive(int $timeToLive = null): Producer
+ public function setTimeToLive(?int $timeToLive = null): Producer
{
$this->timeToLive = $timeToLive;
diff --git a/pkg/mongodb/MongodbSubscriptionConsumer.php b/pkg/mongodb/MongodbSubscriptionConsumer.php
index 59063dd82..9fa6245f4 100644
--- a/pkg/mongodb/MongodbSubscriptionConsumer.php
+++ b/pkg/mongodb/MongodbSubscriptionConsumer.php
@@ -21,9 +21,6 @@ class MongodbSubscriptionConsumer implements SubscriptionConsumer
*/
private $subscribers;
- /**
- * @param MongodbContext $context
- */
public function __construct(MongodbContext $context)
{
$this->context = $context;
@@ -92,7 +89,7 @@ public function consume(int $timeout = 0): void
public function subscribe(Consumer $consumer, callable $callback): void
{
if (false == $consumer instanceof MongodbConsumer) {
- throw new \InvalidArgumentException(sprintf('The consumer must be instance of "%s" got "%s"', MongodbConsumer::class, get_class($consumer)));
+ throw new \InvalidArgumentException(sprintf('The consumer must be instance of "%s" got "%s"', MongodbConsumer::class, $consumer::class));
}
$queueName = $consumer->getQueue()->getQueueName();
@@ -113,7 +110,7 @@ public function subscribe(Consumer $consumer, callable $callback): void
public function unsubscribe(Consumer $consumer): void
{
if (false == $consumer instanceof MongodbConsumer) {
- throw new \InvalidArgumentException(sprintf('The consumer must be instance of "%s" got "%s"', MongodbConsumer::class, get_class($consumer)));
+ throw new \InvalidArgumentException(sprintf('The consumer must be instance of "%s" got "%s"', MongodbConsumer::class, $consumer::class));
}
$queueName = $consumer->getQueue()->getQueueName();
diff --git a/pkg/mongodb/README.md b/pkg/mongodb/README.md
index d29cde0f2..2694dd417 100644
--- a/pkg/mongodb/README.md
+++ b/pkg/mongodb/README.md
@@ -1,27 +1,40 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Mongodb Transport
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/mongodb)
+[](https://github.com/php-enqueue/mongodb/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/mongodb)
[](https://packagist.org/packages/enqueue/mongodb)
-
-This is an implementation of the queue specification. It allows you to use MongoDB database as a message broker.
+
+This is an implementation of the queue specification. It allows you to use MongoDB database as a message broker.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/transport/mongodb/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
-It is released under the [MIT License](LICENSE).
\ No newline at end of file
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/mongodb/Tests/Functional/MongodbConsumerTest.php b/pkg/mongodb/Tests/Functional/MongodbConsumerTest.php
index 609a22e16..b6b644beb 100644
--- a/pkg/mongodb/Tests/Functional/MongodbConsumerTest.php
+++ b/pkg/mongodb/Tests/Functional/MongodbConsumerTest.php
@@ -19,12 +19,12 @@ class MongodbConsumerTest extends TestCase
*/
private $context;
- public function setUp()
+ protected function setUp(): void
{
$this->context = $this->buildMongodbContext();
}
- protected function tearDown()
+ protected function tearDown(): void
{
if ($this->context) {
$this->context->close();
diff --git a/pkg/mongodb/Tests/MongodbConnectionFactoryTest.php b/pkg/mongodb/Tests/MongodbConnectionFactoryTest.php
index 63ec00cea..d5dd9ca45 100644
--- a/pkg/mongodb/Tests/MongodbConnectionFactoryTest.php
+++ b/pkg/mongodb/Tests/MongodbConnectionFactoryTest.php
@@ -5,6 +5,7 @@
use Enqueue\Mongodb\MongodbConnectionFactory;
use Enqueue\Mongodb\MongodbContext;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use Interop\Queue\ConnectionFactory;
use PHPUnit\Framework\TestCase;
@@ -14,6 +15,7 @@
class MongodbConnectionFactoryTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testShouldImplementConnectionFactoryInterface()
{
@@ -45,6 +47,20 @@ public function testCouldBeConstructedWithCustomConfiguration()
$this->assertAttributeEquals($params, 'config', $factory);
}
+ public function testCouldBeConstructedWithCustomConfigurationFromDsn()
+ {
+ $params = [
+ 'dsn' => 'mongodb://127.0.0.3/test-db-name?enqueue_collection=collection-name&polling_interval=3000',
+ 'dbname' => 'test-db-name',
+ 'collection_name' => 'collection-name',
+ 'polling_interval' => 3000,
+ ];
+
+ $factory = new MongodbConnectionFactory($params['dsn']);
+
+ $this->assertAttributeEquals($params, 'config', $factory);
+ }
+
public function testShouldCreateContext()
{
$factory = new MongodbConnectionFactory();
diff --git a/pkg/mongodb/Tests/MongodbConsumerTest.php b/pkg/mongodb/Tests/MongodbConsumerTest.php
index e41681256..6cd597514 100644
--- a/pkg/mongodb/Tests/MongodbConsumerTest.php
+++ b/pkg/mongodb/Tests/MongodbConsumerTest.php
@@ -25,11 +25,6 @@ public function testShouldImplementConsumerInterface()
$this->assertClassImplements(Consumer::class, MongodbConsumer::class);
}
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new MongodbConsumer($this->createContextMock(), new MongodbDestination('queue'));
- }
-
public function testShouldReturnInstanceOfDestination()
{
$destination = new MongodbDestination('queue');
@@ -39,6 +34,9 @@ public function testShouldReturnInstanceOfDestination()
$this->assertSame($destination, $consumer->getQueue());
}
+ /**
+ * @doesNotPerformAssertions
+ */
public function testCouldCallAcknowledgedMethod()
{
$consumer = new MongodbConsumer($this->createContextMock(), new MongodbDestination('queue'));
@@ -104,7 +102,7 @@ public function testRejectShouldReSendMessageToSameQueueOnRequeue()
$context
->expects($this->once())
->method('createProducer')
- ->will($this->returnValue($producerMock))
+ ->willReturn($producerMock)
;
$consumer = new MongodbConsumer($context, $queue);
@@ -113,7 +111,7 @@ public function testRejectShouldReSendMessageToSameQueueOnRequeue()
}
/**
- * @return MongodbProducer|\PHPUnit_Framework_MockObject_MockObject
+ * @return MongodbProducer|\PHPUnit\Framework\MockObject\MockObject
*/
private function createProducerMock()
{
@@ -121,7 +119,7 @@ private function createProducerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|MongodbContext
+ * @return \PHPUnit\Framework\MockObject\MockObject|MongodbContext
*/
private function createContextMock()
{
@@ -133,6 +131,7 @@ class InvalidMessage implements Message
{
public function getBody(): string
{
+ throw new \BadMethodCallException('This should not be called directly');
}
public function setBody(string $body): void
@@ -145,6 +144,7 @@ public function setProperties(array $properties): void
public function getProperties(): array
{
+ throw new \BadMethodCallException('This should not be called directly');
}
public function setProperty(string $name, $value): void
@@ -161,6 +161,7 @@ public function setHeaders(array $headers): void
public function getHeaders(): array
{
+ throw new \BadMethodCallException('This should not be called directly');
}
public function setHeader(string $name, $value): void
@@ -177,37 +178,42 @@ public function setRedelivered(bool $redelivered): void
public function isRedelivered(): bool
{
+ throw new \BadMethodCallException('This should not be called directly');
}
- public function setCorrelationId(string $correlationId = null): void
+ public function setCorrelationId(?string $correlationId = null): void
{
}
public function getCorrelationId(): ?string
{
+ throw new \BadMethodCallException('This should not be called directly');
}
- public function setMessageId(string $messageId = null): void
+ public function setMessageId(?string $messageId = null): void
{
}
public function getMessageId(): ?string
{
+ throw new \BadMethodCallException('This should not be called directly');
}
public function getTimestamp(): ?int
{
+ throw new \BadMethodCallException('This should not be called directly');
}
- public function setTimestamp(int $timestamp = null): void
+ public function setTimestamp(?int $timestamp = null): void
{
}
- public function setReplyTo(string $replyTo = null): void
+ public function setReplyTo(?string $replyTo = null): void
{
}
public function getReplyTo(): ?string
{
+ throw new \BadMethodCallException('This should not be called directly');
}
}
diff --git a/pkg/mongodb/Tests/MongodbContextTest.php b/pkg/mongodb/Tests/MongodbContextTest.php
index d43f21733..8cdef79ff 100644
--- a/pkg/mongodb/Tests/MongodbContextTest.php
+++ b/pkg/mongodb/Tests/MongodbContextTest.php
@@ -8,6 +8,7 @@
use Enqueue\Mongodb\MongodbMessage;
use Enqueue\Mongodb\MongodbProducer;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use Interop\Queue\Context;
use Interop\Queue\Destination;
use Interop\Queue\Exception\InvalidDestinationException;
@@ -21,17 +22,13 @@
class MongodbContextTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testShouldImplementContextInterface()
{
$this->assertClassImplements(Context::class, MongodbContext::class);
}
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new MongodbContext($this->createClientMock());
- }
-
public function testCouldBeConstructedWithEmptyConfiguration()
{
$context = new MongodbContext($this->createClientMock(), []);
@@ -183,7 +180,7 @@ public function testShouldThrowNotSupportedOnCreateTemporaryQueueCall()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Client
+ * @return \PHPUnit\Framework\MockObject\MockObject|Client
*/
private function createClientMock()
{
diff --git a/pkg/mongodb/Tests/MongodbProducerTest.php b/pkg/mongodb/Tests/MongodbProducerTest.php
index a62c8436e..6987b1a76 100644
--- a/pkg/mongodb/Tests/MongodbProducerTest.php
+++ b/pkg/mongodb/Tests/MongodbProducerTest.php
@@ -23,11 +23,6 @@ public function testShouldImplementProducerInterface()
$this->assertClassImplements(Producer::class, MongodbProducer::class);
}
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new MongodbProducer($this->createContextMock());
- }
-
public function testShouldThrowIfDestinationOfInvalidType()
{
$this->expectException(InvalidDestinationException::class);
@@ -43,7 +38,7 @@ public function testShouldThrowIfDestinationOfInvalidType()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|MongodbContext
+ * @return \PHPUnit\Framework\MockObject\MockObject|MongodbContext
*/
private function createContextMock()
{
diff --git a/pkg/mongodb/Tests/MongodbSubscriptionConsumerTest.php b/pkg/mongodb/Tests/MongodbSubscriptionConsumerTest.php
index 88899c7bb..d982e0418 100644
--- a/pkg/mongodb/Tests/MongodbSubscriptionConsumerTest.php
+++ b/pkg/mongodb/Tests/MongodbSubscriptionConsumerTest.php
@@ -7,6 +7,7 @@
use Enqueue\Mongodb\MongodbConsumer;
use Enqueue\Mongodb\MongodbContext;
use Enqueue\Mongodb\MongodbSubscriptionConsumer;
+use Enqueue\Test\ReadAttributeTrait;
use Interop\Queue\Consumer;
use Interop\Queue\Queue;
use Interop\Queue\SubscriptionConsumer;
@@ -14,6 +15,8 @@
class MongodbSubscriptionConsumerTest extends TestCase
{
+ use ReadAttributeTrait;
+
public function testShouldImplementSubscriptionConsumerInterface()
{
$rc = new \ReflectionClass(MongodbSubscriptionConsumer::class);
@@ -21,11 +24,6 @@ public function testShouldImplementSubscriptionConsumerInterface()
$this->assertTrue($rc->implementsInterface(SubscriptionConsumer::class));
}
- public function testCouldBeConstructedWithMongodbContextAsFirstArgument()
- {
- new MongodbSubscriptionConsumer($this->createMongodbContextMock());
- }
-
public function testShouldAddConsumerAndCallbackToSubscribersPropertyOnSubscribe()
{
$subscriptionConsumer = new MongodbSubscriptionConsumer($this->createMongodbContextMock());
@@ -62,6 +60,9 @@ public function testThrowsIfTrySubscribeAnotherConsumerToAlreadySubscribedQueue(
$subscriptionConsumer->subscribe($barConsumer, $barCallback);
}
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldAllowSubscribeSameConsumerAndCallbackSecondTime()
{
$subscriptionConsumer = new MongodbSubscriptionConsumer($this->createMongodbContextMock());
@@ -145,7 +146,7 @@ public function testThrowsIfTryConsumeWithoutSubscribers()
}
/**
- * @return MongodbContext|\PHPUnit_Framework_MockObject_MockObject
+ * @return MongodbContext|\PHPUnit\Framework\MockObject\MockObject
*/
private function createMongodbContextMock()
{
@@ -153,9 +154,9 @@ private function createMongodbContextMock()
}
/**
- * @param null|mixed $queueName
+ * @param mixed|null $queueName
*
- * @return Consumer|\PHPUnit_Framework_MockObject_MockObject
+ * @return Consumer|\PHPUnit\Framework\MockObject\MockObject
*/
private function createConsumerStub($queueName = null)
{
diff --git a/pkg/mongodb/Tests/Spec/MongodbConnectionFactoryTest.php b/pkg/mongodb/Tests/Spec/MongodbConnectionFactoryTest.php
index 359b23eff..9f0d195ba 100644
--- a/pkg/mongodb/Tests/Spec/MongodbConnectionFactoryTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbConnectionFactoryTest.php
@@ -10,9 +10,6 @@
*/
class MongodbConnectionFactoryTest extends ConnectionFactorySpec
{
- /**
- * {@inheritdoc}
- */
protected function createConnectionFactory()
{
return new MongodbConnectionFactory();
diff --git a/pkg/mongodb/Tests/Spec/MongodbContextTest.php b/pkg/mongodb/Tests/Spec/MongodbContextTest.php
index 22f2f3210..dfd5de3cb 100644
--- a/pkg/mongodb/Tests/Spec/MongodbContextTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbContextTest.php
@@ -13,9 +13,6 @@ class MongodbContextTest extends ContextSpec
{
use MongodbExtensionTrait;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildMongodbContext();
diff --git a/pkg/mongodb/Tests/Spec/MongodbMessageTest.php b/pkg/mongodb/Tests/Spec/MongodbMessageTest.php
index 5efccfa01..92983d430 100644
--- a/pkg/mongodb/Tests/Spec/MongodbMessageTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbMessageTest.php
@@ -10,9 +10,6 @@
*/
class MongodbMessageTest extends MessageSpec
{
- /**
- * {@inheritdoc}
- */
protected function createMessage()
{
return new MongodbMessage();
diff --git a/pkg/mongodb/Tests/Spec/MongodbProducerTest.php b/pkg/mongodb/Tests/Spec/MongodbProducerTest.php
index 9b4e18793..68b6007ec 100644
--- a/pkg/mongodb/Tests/Spec/MongodbProducerTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbProducerTest.php
@@ -13,9 +13,6 @@ class MongodbProducerTest extends ProducerSpec
{
use MongodbExtensionTrait;
- /**
- * {@inheritdoc}
- */
protected function createProducer()
{
return $this->buildMongodbContext()->createProducer();
diff --git a/pkg/mongodb/Tests/Spec/MongodbQueueTest.php b/pkg/mongodb/Tests/Spec/MongodbQueueTest.php
index f737d765f..25e437ba6 100644
--- a/pkg/mongodb/Tests/Spec/MongodbQueueTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbQueueTest.php
@@ -10,9 +10,6 @@
*/
class MongodbQueueTest extends QueueSpec
{
- /**
- * {@inheritdoc}
- */
protected function createQueue()
{
return new MongodbDestination(self::EXPECTED_QUEUE_NAME);
diff --git a/pkg/mongodb/Tests/Spec/MongodbRequeueMessageTest.php b/pkg/mongodb/Tests/Spec/MongodbRequeueMessageTest.php
index 454d357ad..8a9072470 100644
--- a/pkg/mongodb/Tests/Spec/MongodbRequeueMessageTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbRequeueMessageTest.php
@@ -13,9 +13,6 @@ class MongodbRequeueMessageTest extends RequeueMessageSpec
{
use MongodbExtensionTrait;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildMongodbContext();
diff --git a/pkg/mongodb/Tests/Spec/MongodbSendAndReceiveDelayedMessageFromQueueTest.php b/pkg/mongodb/Tests/Spec/MongodbSendAndReceiveDelayedMessageFromQueueTest.php
index a5eb3511d..f54513fae 100644
--- a/pkg/mongodb/Tests/Spec/MongodbSendAndReceiveDelayedMessageFromQueueTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbSendAndReceiveDelayedMessageFromQueueTest.php
@@ -13,9 +13,6 @@ class MongodbSendAndReceiveDelayedMessageFromQueueTest extends SendAndReceiveDel
{
use MongodbExtensionTrait;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildMongodbContext();
diff --git a/pkg/mongodb/Tests/Spec/MongodbSendAndReceivePriorityMessagesFromQueueTest.php b/pkg/mongodb/Tests/Spec/MongodbSendAndReceivePriorityMessagesFromQueueTest.php
index 9869d6e06..6aadef7ba 100644
--- a/pkg/mongodb/Tests/Spec/MongodbSendAndReceivePriorityMessagesFromQueueTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbSendAndReceivePriorityMessagesFromQueueTest.php
@@ -18,7 +18,7 @@ class MongodbSendAndReceivePriorityMessagesFromQueueTest extends SendAndReceiveP
private $publishedAt;
- public function setUp()
+ protected function setUp(): void
{
parent::setUp();
@@ -34,8 +34,6 @@ protected function createContext()
}
/**
- * {@inheritdoc}
- *
* @param MongodbContext $context
*
* @return MongodbMessage
diff --git a/pkg/mongodb/Tests/Spec/MongodbSendAndReceiveTimeToLiveMessagesFromQueueTest.php b/pkg/mongodb/Tests/Spec/MongodbSendAndReceiveTimeToLiveMessagesFromQueueTest.php
index d87ac10e9..f16e80b60 100644
--- a/pkg/mongodb/Tests/Spec/MongodbSendAndReceiveTimeToLiveMessagesFromQueueTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbSendAndReceiveTimeToLiveMessagesFromQueueTest.php
@@ -13,9 +13,6 @@ class MongodbSendAndReceiveTimeToLiveMessagesFromQueueTest extends SendAndReceiv
{
use MongodbExtensionTrait;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildMongodbContext();
diff --git a/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveFromQueueTest.php b/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveFromQueueTest.php
index 992c0626e..c9b9cb2d1 100644
--- a/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveFromQueueTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveFromQueueTest.php
@@ -13,9 +13,6 @@ class MongodbSendToAndReceiveFromQueueTest extends SendToAndReceiveFromQueueSpec
{
use MongodbExtensionTrait;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildMongodbContext();
diff --git a/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveFromTopicTest.php b/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveFromTopicTest.php
index c539386f7..a416d3c11 100644
--- a/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveFromTopicTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveFromTopicTest.php
@@ -13,9 +13,6 @@ class MongodbSendToAndReceiveFromTopicTest extends SendToAndReceiveFromTopicSpec
{
use MongodbExtensionTrait;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildMongodbContext();
diff --git a/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveNoWaitFromQueueTest.php b/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveNoWaitFromQueueTest.php
index ea4febcc2..43ae34c6b 100644
--- a/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveNoWaitFromQueueTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveNoWaitFromQueueTest.php
@@ -13,9 +13,6 @@ class MongodbSendToAndReceiveNoWaitFromQueueTest extends SendToAndReceiveNoWaitF
{
use MongodbExtensionTrait;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildMongodbContext();
diff --git a/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveNoWaitFromTopicTest.php b/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveNoWaitFromTopicTest.php
index 1e1be32c1..0fe9f0e56 100644
--- a/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveNoWaitFromTopicTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbSendToAndReceiveNoWaitFromTopicTest.php
@@ -13,9 +13,6 @@ class MongodbSendToAndReceiveNoWaitFromTopicTest extends SendToAndReceiveNoWaitF
{
use MongodbExtensionTrait;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildMongodbContext();
diff --git a/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerConsumeFromAllSubscribedQueuesTest.php b/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerConsumeFromAllSubscribedQueuesTest.php
index 664990a68..2fe16e860 100644
--- a/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerConsumeFromAllSubscribedQueuesTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerConsumeFromAllSubscribedQueuesTest.php
@@ -20,8 +20,6 @@ class MongodbSubscriptionConsumerConsumeFromAllSubscribedQueuesTest extends Subs
/**
* @return MongodbContext
- *
- * {@inheritdoc}
*/
protected function createContext()
{
@@ -30,8 +28,6 @@ protected function createContext()
/**
* @param MongodbContext $context
- *
- * {@inheritdoc}
*/
protected function createQueue(Context $context, $queueName)
{
diff --git a/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerConsumeUntilUnsubscribedTest.php b/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerConsumeUntilUnsubscribedTest.php
index 1071c1267..b18e0bf0d 100644
--- a/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerConsumeUntilUnsubscribedTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerConsumeUntilUnsubscribedTest.php
@@ -20,8 +20,6 @@ class MongodbSubscriptionConsumerConsumeUntilUnsubscribedTest extends Subscripti
/**
* @return MongodbContext
- *
- * {@inheritdoc}
*/
protected function createContext()
{
@@ -30,8 +28,6 @@ protected function createContext()
/**
* @param MongodbContext $context
- *
- * {@inheritdoc}
*/
protected function createQueue(Context $context, $queueName)
{
diff --git a/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerStopOnFalseTest.php b/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerStopOnFalseTest.php
index 321e16bba..3acfa94ed 100644
--- a/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerStopOnFalseTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbSubscriptionConsumerStopOnFalseTest.php
@@ -20,8 +20,6 @@ class MongodbSubscriptionConsumerStopOnFalseTest extends SubscriptionConsumerSto
/**
* @return MongodbContext
- *
- * {@inheritdoc}
*/
protected function createContext()
{
@@ -30,8 +28,6 @@ protected function createContext()
/**
* @param MongodbContext $context
- *
- * {@inheritdoc}
*/
protected function createQueue(Context $context, $queueName)
{
diff --git a/pkg/mongodb/Tests/Spec/MongodbTopicTest.php b/pkg/mongodb/Tests/Spec/MongodbTopicTest.php
index ec524e519..ab5c025a2 100644
--- a/pkg/mongodb/Tests/Spec/MongodbTopicTest.php
+++ b/pkg/mongodb/Tests/Spec/MongodbTopicTest.php
@@ -10,9 +10,6 @@
*/
class MongodbTopicTest extends TopicSpec
{
- /**
- * {@inheritdoc}
- */
protected function createTopic()
{
return new MongodbDestination(self::EXPECTED_TOPIC_NAME);
diff --git a/pkg/mongodb/composer.json b/pkg/mongodb/composer.json
index 11bd5ae24..f64d53ef3 100644
--- a/pkg/mongodb/composer.json
+++ b/pkg/mongodb/composer.json
@@ -10,16 +10,16 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "queue-interop/queue-interop": "0.7.x-dev",
+ "php": "^8.1",
+ "queue-interop/queue-interop": "^0.8",
"mongodb/mongodb": "^1.2",
- "ext-mongodb": "^1.3"
+ "ext-mongodb": "^1.5"
},
"require-dev": {
- "phpunit/phpunit": "~5.4.0",
- "queue-interop/queue-spec": "0.6.x-dev",
- "enqueue/test": "0.9.x-dev",
- "enqueue/null": "0.9.x-dev"
+ "phpunit/phpunit": "^9.5",
+ "queue-interop/queue-spec": "^0.6.2",
+ "enqueue/test": "0.10.x-dev",
+ "enqueue/null": "0.10.x-dev"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -37,7 +37,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/mongodb/phpunit.xml.dist b/pkg/mongodb/phpunit.xml.dist
index 1f34af01d..6b9960935 100644
--- a/pkg/mongodb/phpunit.xml.dist
+++ b/pkg/mongodb/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/monitoring/.gitattributes b/pkg/monitoring/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/monitoring/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/monitoring/.github/workflows/ci.yml b/pkg/monitoring/.github/workflows/ci.yml
new file mode 100644
index 000000000..ce80335de
--- /dev/null
+++ b/pkg/monitoring/.github/workflows/ci.yml
@@ -0,0 +1,27 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/monitoring/.gitignore b/pkg/monitoring/.gitignore
new file mode 100644
index 000000000..a770439e5
--- /dev/null
+++ b/pkg/monitoring/.gitignore
@@ -0,0 +1,6 @@
+*~
+/composer.lock
+/composer.phar
+/phpunit.xml
+/vendor/
+/.idea/
diff --git a/pkg/monitoring/ClientMonitoringExtension.php b/pkg/monitoring/ClientMonitoringExtension.php
new file mode 100644
index 000000000..11e7054f7
--- /dev/null
+++ b/pkg/monitoring/ClientMonitoringExtension.php
@@ -0,0 +1,64 @@
+storage = $storage;
+ $this->logger = $logger;
+ }
+
+ public function onPostSend(PostSend $context): void
+ {
+ $timestampMs = (int) (microtime(true) * 1000);
+
+ $destination = $context->getTransportDestination() instanceof Topic
+ ? $context->getTransportDestination()->getTopicName()
+ : $context->getTransportDestination()->getQueueName()
+ ;
+
+ $stats = new SentMessageStats(
+ $timestampMs,
+ $destination,
+ $context->getTransportDestination() instanceof Topic,
+ $context->getTransportMessage()->getMessageId(),
+ $context->getTransportMessage()->getCorrelationId(),
+ $context->getTransportMessage()->getHeaders(),
+ $context->getTransportMessage()->getProperties()
+ );
+
+ $this->safeCall(function () use ($stats) {
+ $this->storage->pushSentMessageStats($stats);
+ });
+ }
+
+ private function safeCall(callable $fun)
+ {
+ try {
+ return call_user_func($fun);
+ } catch (\Throwable $e) {
+ $this->logger->error(sprintf('[ClientMonitoringExtension] Push to storage failed: %s', $e->getMessage()));
+ }
+
+ return null;
+ }
+}
diff --git a/pkg/monitoring/ConsumedMessageStats.php b/pkg/monitoring/ConsumedMessageStats.php
new file mode 100644
index 000000000..077ceebdf
--- /dev/null
+++ b/pkg/monitoring/ConsumedMessageStats.php
@@ -0,0 +1,210 @@
+consumerId = $consumerId;
+ $this->timestampMs = $timestampMs;
+ $this->receivedAtMs = $receivedAtMs;
+ $this->queue = $queue;
+ $this->messageId = $messageId;
+ $this->correlationId = $correlationId;
+ $this->headers = $headers;
+ $this->properties = $properties;
+ $this->redelivered = $redelivered;
+ $this->status = $status;
+
+ $this->errorClass = $errorClass;
+ $this->errorMessage = $errorMessage;
+ $this->errorCode = $errorCode;
+ $this->errorFile = $errorFile;
+ $this->errorLine = $errorLine;
+ $this->trance = $trace;
+ }
+
+ public function getConsumerId(): string
+ {
+ return $this->consumerId;
+ }
+
+ public function getTimestampMs(): int
+ {
+ return $this->timestampMs;
+ }
+
+ public function getReceivedAtMs(): int
+ {
+ return $this->receivedAtMs;
+ }
+
+ public function getQueue(): string
+ {
+ return $this->queue;
+ }
+
+ public function getMessageId(): ?string
+ {
+ return $this->messageId;
+ }
+
+ public function getCorrelationId(): ?string
+ {
+ return $this->correlationId;
+ }
+
+ public function getHeaders(): array
+ {
+ return $this->headers;
+ }
+
+ public function getProperties(): array
+ {
+ return $this->properties;
+ }
+
+ public function isRedelivered(): bool
+ {
+ return $this->redelivered;
+ }
+
+ public function getStatus(): string
+ {
+ return $this->status;
+ }
+
+ public function getErrorClass(): ?string
+ {
+ return $this->errorClass;
+ }
+
+ public function getErrorMessage(): ?string
+ {
+ return $this->errorMessage;
+ }
+
+ public function getErrorCode(): ?int
+ {
+ return $this->errorCode;
+ }
+
+ public function getErrorFile(): ?string
+ {
+ return $this->errorFile;
+ }
+
+ public function getErrorLine(): ?int
+ {
+ return $this->errorLine;
+ }
+
+ public function getTrance(): ?string
+ {
+ return $this->trance;
+ }
+}
diff --git a/pkg/monitoring/ConsumerMonitoringExtension.php b/pkg/monitoring/ConsumerMonitoringExtension.php
new file mode 100644
index 000000000..31e97697d
--- /dev/null
+++ b/pkg/monitoring/ConsumerMonitoringExtension.php
@@ -0,0 +1,320 @@
+storage = $storage;
+ $this->updateStatsPeriod = 60;
+ }
+
+ public function onStart(Start $context): void
+ {
+ $this->consumerId = UUID::generate();
+
+ $this->queues = [];
+
+ $this->startedAtMs = 0;
+ $this->lastStatsAt = 0;
+
+ $this->received = 0;
+ $this->acknowledged = 0;
+ $this->rejected = 0;
+ $this->requeued = 0;
+ }
+
+ public function onPreSubscribe(PreSubscribe $context): void
+ {
+ $this->queues[] = $context->getConsumer()->getQueue()->getQueueName();
+ }
+
+ public function onPreConsume(PreConsume $context): void
+ {
+ // send started only once
+ $isStarted = false;
+ if (0 === $this->startedAtMs) {
+ $isStarted = true;
+ $this->startedAtMs = $context->getStartTime();
+ }
+
+ // send stats event only once per period
+ $time = time();
+ if (($time - $this->lastStatsAt) > $this->updateStatsPeriod) {
+ $this->lastStatsAt = $time;
+
+ $event = new ConsumerStats(
+ $this->consumerId,
+ $this->getNowMs(),
+ $this->startedAtMs,
+ null,
+ $isStarted,
+ false,
+ false,
+ $this->queues,
+ $this->received,
+ $this->acknowledged,
+ $this->rejected,
+ $this->requeued,
+ $this->getMemoryUsage(),
+ $this->getSystemLoad()
+ );
+
+ $this->safeCall(function () use ($event) {
+ $this->storage->pushConsumerStats($event);
+ }, $context->getLogger());
+ }
+ }
+
+ public function onEnd(End $context): void
+ {
+ $event = new ConsumerStats(
+ $this->consumerId,
+ $this->getNowMs(),
+ $this->startedAtMs,
+ $context->getEndTime(),
+ false,
+ true,
+ false,
+ $this->queues,
+ $this->received,
+ $this->acknowledged,
+ $this->rejected,
+ $this->requeued,
+ $this->getMemoryUsage(),
+ $this->getSystemLoad()
+ );
+
+ $this->safeCall(function () use ($event) {
+ $this->storage->pushConsumerStats($event);
+ }, $context->getLogger());
+ }
+
+ public function onProcessorException(ProcessorException $context): void
+ {
+ $timeMs = $this->getNowMs();
+
+ $event = new ConsumedMessageStats(
+ $this->consumerId,
+ $timeMs,
+ $context->getReceivedAt(),
+ $context->getConsumer()->getQueue()->getQueueName(),
+ $context->getMessage()->getMessageId(),
+ $context->getMessage()->getCorrelationId(),
+ $context->getMessage()->getHeaders(),
+ $context->getMessage()->getProperties(),
+ $context->getMessage()->isRedelivered(),
+ ConsumedMessageStats::STATUS_FAILED,
+ get_class($context->getException()),
+ $context->getException()->getMessage(),
+ $context->getException()->getCode(),
+ $context->getException()->getFile(),
+ $context->getException()->getLine(),
+ $context->getException()->getTraceAsString()
+ );
+
+ $this->safeCall(function () use ($event) {
+ $this->storage->pushConsumedMessageStats($event);
+ }, $context->getLogger());
+
+ // priority of this extension must be the lowest and
+ // if result is null we emit consumer stopped event here
+ if (null === $context->getResult()) {
+ $event = new ConsumerStats(
+ $this->consumerId,
+ $timeMs,
+ $this->startedAtMs,
+ $timeMs,
+ false,
+ true,
+ true,
+ $this->queues,
+ $this->received,
+ $this->acknowledged,
+ $this->rejected,
+ $this->requeued,
+ $this->getMemoryUsage(),
+ $this->getSystemLoad(),
+ get_class($context->getException()),
+ $context->getException()->getMessage(),
+ $context->getException()->getCode(),
+ $context->getException()->getFile(),
+ $context->getException()->getLine(),
+ $context->getException()->getTraceAsString()
+ );
+
+ $this->safeCall(function () use ($event) {
+ $this->storage->pushConsumerStats($event);
+ }, $context->getLogger());
+ }
+ }
+
+ public function onMessageReceived(MessageReceived $context): void
+ {
+ ++$this->received;
+ }
+
+ public function onResult(MessageResult $context): void
+ {
+ $timeMs = $this->getNowMs();
+
+ switch ($context->getResult()) {
+ case Result::ACK:
+ case Result::ALREADY_ACKNOWLEDGED:
+ $this->acknowledged++;
+ $status = ConsumedMessageStats::STATUS_ACK;
+ break;
+ case Result::REJECT:
+ $this->rejected++;
+ $status = ConsumedMessageStats::STATUS_REJECTED;
+ break;
+ case Result::REQUEUE:
+ $this->requeued++;
+ $status = ConsumedMessageStats::STATUS_REQUEUED;
+ break;
+ default:
+ throw new \LogicException();
+ }
+
+ $event = new ConsumedMessageStats(
+ $this->consumerId,
+ $timeMs,
+ $context->getReceivedAt(),
+ $context->getConsumer()->getQueue()->getQueueName(),
+ $context->getMessage()->getMessageId(),
+ $context->getMessage()->getCorrelationId(),
+ $context->getMessage()->getHeaders(),
+ $context->getMessage()->getProperties(),
+ $context->getMessage()->isRedelivered(),
+ $status
+ );
+
+ $this->safeCall(function () use ($event) {
+ $this->storage->pushConsumedMessageStats($event);
+ }, $context->getLogger());
+
+ // send stats event only once per period
+ $time = time();
+ if (($time - $this->lastStatsAt) > $this->updateStatsPeriod) {
+ $this->lastStatsAt = $time;
+
+ $event = new ConsumerStats(
+ $this->consumerId,
+ $timeMs,
+ $this->startedAtMs,
+ null,
+ false,
+ false,
+ false,
+ $this->queues,
+ $this->received,
+ $this->acknowledged,
+ $this->rejected,
+ $this->requeued,
+ $this->getMemoryUsage(),
+ $this->getSystemLoad()
+ );
+
+ $this->safeCall(function () use ($event) {
+ $this->storage->pushConsumerStats($event);
+ }, $context->getLogger());
+ }
+ }
+
+ private function getNowMs(): int
+ {
+ return (int) (microtime(true) * 1000);
+ }
+
+ private function getMemoryUsage(): int
+ {
+ return memory_get_usage(true);
+ }
+
+ private function getSystemLoad(): float
+ {
+ return sys_getloadavg()[0];
+ }
+
+ private function safeCall(callable $fun, LoggerInterface $logger)
+ {
+ try {
+ return call_user_func($fun);
+ } catch (\Throwable $e) {
+ $logger->error(sprintf('[ConsumerMonitoringExtension] Push to storage failed: %s', $e->getMessage()));
+ }
+
+ return null;
+ }
+}
diff --git a/pkg/monitoring/ConsumerStats.php b/pkg/monitoring/ConsumerStats.php
new file mode 100644
index 000000000..d281b532d
--- /dev/null
+++ b/pkg/monitoring/ConsumerStats.php
@@ -0,0 +1,257 @@
+consumerId = $consumerId;
+ $this->timestampMs = $timestampMs;
+ $this->startedAtMs = $startedAtMs;
+ $this->finishedAtMs = $finishedAtMs;
+
+ $this->started = $started;
+ $this->finished = $finished;
+ $this->failed = $failed;
+
+ $this->queues = $queues;
+ $this->startedAtMs = $startedAtMs;
+ $this->received = $received;
+ $this->acknowledged = $acknowledged;
+ $this->rejected = $rejected;
+ $this->requeued = $requeued;
+
+ $this->memoryUsage = $memoryUsage;
+ $this->systemLoad = $systemLoad;
+
+ $this->errorClass = $errorClass;
+ $this->errorMessage = $errorMessage;
+ $this->errorCode = $errorCode;
+ $this->errorFile = $errorFile;
+ $this->errorLine = $errorLine;
+ $this->trance = $trace;
+ }
+
+ public function getConsumerId(): string
+ {
+ return $this->consumerId;
+ }
+
+ public function getTimestampMs(): int
+ {
+ return $this->timestampMs;
+ }
+
+ public function getStartedAtMs(): int
+ {
+ return $this->startedAtMs;
+ }
+
+ public function getFinishedAtMs(): ?int
+ {
+ return $this->finishedAtMs;
+ }
+
+ public function isStarted(): bool
+ {
+ return $this->started;
+ }
+
+ public function isFinished(): bool
+ {
+ return $this->finished;
+ }
+
+ public function isFailed(): bool
+ {
+ return $this->failed;
+ }
+
+ public function getQueues(): array
+ {
+ return $this->queues;
+ }
+
+ public function getReceived(): int
+ {
+ return $this->received;
+ }
+
+ public function getAcknowledged(): int
+ {
+ return $this->acknowledged;
+ }
+
+ public function getRejected(): int
+ {
+ return $this->rejected;
+ }
+
+ public function getRequeued(): int
+ {
+ return $this->requeued;
+ }
+
+ public function getMemoryUsage(): int
+ {
+ return $this->memoryUsage;
+ }
+
+ public function getSystemLoad(): float
+ {
+ return $this->systemLoad;
+ }
+
+ public function getErrorClass(): ?string
+ {
+ return $this->errorClass;
+ }
+
+ public function getErrorMessage(): ?string
+ {
+ return $this->errorMessage;
+ }
+
+ public function getErrorCode(): ?int
+ {
+ return $this->errorCode;
+ }
+
+ public function getErrorFile(): ?string
+ {
+ return $this->errorFile;
+ }
+
+ public function getErrorLine(): ?int
+ {
+ return $this->errorLine;
+ }
+
+ public function getTrance(): ?string
+ {
+ return $this->trance;
+ }
+}
diff --git a/pkg/monitoring/DatadogStorage.php b/pkg/monitoring/DatadogStorage.php
new file mode 100644
index 000000000..c10cbc671
--- /dev/null
+++ b/pkg/monitoring/DatadogStorage.php
@@ -0,0 +1,165 @@
+config = $this->prepareConfig($config);
+
+ if (null === $this->datadog) {
+ if (true === filter_var($this->config['batched'], \FILTER_VALIDATE_BOOLEAN)) {
+ $this->datadog = new BatchedDogStatsd($this->config);
+ } else {
+ $this->datadog = new DogStatsd($this->config);
+ }
+ }
+ }
+
+ public function pushConsumerStats(ConsumerStats $stats): void
+ {
+ $queues = $stats->getQueues();
+ array_walk($queues, function (string $queue) use ($stats) {
+ $tags = [
+ 'queue' => $queue,
+ 'consumerId' => $stats->getConsumerId(),
+ ];
+
+ if ($stats->getFinishedAtMs()) {
+ $values['finishedAtMs'] = $stats->getFinishedAtMs();
+ }
+
+ $this->datadog->gauge($this->config['metric.consumers.started'], (int) $stats->isStarted(), 1, $tags);
+ $this->datadog->gauge($this->config['metric.consumers.finished'], (int) $stats->isFinished(), 1, $tags);
+ $this->datadog->gauge($this->config['metric.consumers.failed'], (int) $stats->isFailed(), 1, $tags);
+ $this->datadog->gauge($this->config['metric.consumers.received'], $stats->getReceived(), 1, $tags);
+ $this->datadog->gauge($this->config['metric.consumers.acknowledged'], $stats->getAcknowledged(), 1, $tags);
+ $this->datadog->gauge($this->config['metric.consumers.rejected'], $stats->getRejected(), 1, $tags);
+ $this->datadog->gauge($this->config['metric.consumers.requeued'], $stats->getRejected(), 1, $tags);
+ $this->datadog->gauge($this->config['metric.consumers.memoryUsage'], $stats->getMemoryUsage(), 1, $tags);
+ });
+ }
+
+ public function pushSentMessageStats(SentMessageStats $stats): void
+ {
+ $tags = [
+ 'destination' => $stats->getDestination(),
+ ];
+
+ $properties = $stats->getProperties();
+ if (false === empty($properties[Config::TOPIC])) {
+ $tags['topic'] = $properties[Config::TOPIC];
+ }
+
+ if (false === empty($properties[Config::COMMAND])) {
+ $tags['command'] = $properties[Config::COMMAND];
+ }
+
+ $this->datadog->increment($this->config['metric.messages.sent'], 1, $tags);
+ }
+
+ public function pushConsumedMessageStats(ConsumedMessageStats $stats): void
+ {
+ $tags = [
+ 'queue' => $stats->getQueue(),
+ 'status' => $stats->getStatus(),
+ ];
+
+ if (ConsumedMessageStats::STATUS_FAILED === $stats->getStatus()) {
+ $this->datadog->increment($this->config['metric.messages.failed'], 1, $tags);
+ }
+
+ if ($stats->isRedelivered()) {
+ $this->datadog->increment($this->config['metric.messages.redelivered'], 1, $tags);
+ }
+
+ $runtime = $stats->getTimestampMs() - $stats->getReceivedAtMs();
+ $this->datadog->histogram($this->config['metric.messages.consumed'], $runtime, 1, $tags);
+ }
+
+ private function parseDsn(string $dsn): array
+ {
+ $dsn = Dsn::parseFirst($dsn);
+
+ if ('datadog' !== $dsn->getSchemeProtocol()) {
+ throw new \LogicException(sprintf('The given scheme protocol "%s" is not supported. It must be "datadog"', $dsn->getSchemeProtocol()));
+ }
+
+ return array_filter(array_replace($dsn->getQuery(), [
+ 'host' => $dsn->getHost(),
+ 'port' => $dsn->getPort(),
+ 'global_tags' => $dsn->getString('global_tags'),
+ 'batched' => $dsn->getString('batched'),
+ 'metric.messages.sent' => $dsn->getString('metric.messages.sent'),
+ 'metric.messages.consumed' => $dsn->getString('metric.messages.consumed'),
+ 'metric.messages.redelivered' => $dsn->getString('metric.messages.redelivered'),
+ 'metric.messages.failed' => $dsn->getString('metric.messages.failed'),
+ 'metric.consumers.started' => $dsn->getString('metric.consumers.started'),
+ 'metric.consumers.finished' => $dsn->getString('metric.consumers.finished'),
+ 'metric.consumers.failed' => $dsn->getString('metric.consumers.failed'),
+ 'metric.consumers.received' => $dsn->getString('metric.consumers.received'),
+ 'metric.consumers.acknowledged' => $dsn->getString('metric.consumers.acknowledged'),
+ 'metric.consumers.rejected' => $dsn->getString('metric.consumers.rejected'),
+ 'metric.consumers.requeued' => $dsn->getString('metric.consumers.requeued'),
+ 'metric.consumers.memoryUsage' => $dsn->getString('metric.consumers.memoryUsage'),
+ ]), function ($value) {
+ return null !== $value;
+ });
+ }
+
+ private function prepareConfig($config): array
+ {
+ if (empty($config)) {
+ $config = $this->parseDsn('datadog:');
+ } elseif (\is_string($config)) {
+ $config = $this->parseDsn($config);
+ } elseif (\is_array($config)) {
+ $config = empty($config['dsn']) ? $config : $this->parseDsn($config['dsn']);
+ } elseif ($config instanceof DogStatsd) {
+ $this->datadog = $config;
+ $config = [];
+ } else {
+ throw new \LogicException('The config must be either an array of options, a DSN string or null');
+ }
+
+ return array_replace([
+ 'host' => 'localhost',
+ 'port' => 8125,
+ 'batched' => true,
+ 'metric.messages.sent' => 'enqueue.messages.sent',
+ 'metric.messages.consumed' => 'enqueue.messages.consumed',
+ 'metric.messages.redelivered' => 'enqueue.messages.redelivered',
+ 'metric.messages.failed' => 'enqueue.messages.failed',
+ 'metric.consumers.started' => 'enqueue.consumers.started',
+ 'metric.consumers.finished' => 'enqueue.consumers.finished',
+ 'metric.consumers.failed' => 'enqueue.consumers.failed',
+ 'metric.consumers.received' => 'enqueue.consumers.received',
+ 'metric.consumers.acknowledged' => 'enqueue.consumers.acknowledged',
+ 'metric.consumers.rejected' => 'enqueue.consumers.rejected',
+ 'metric.consumers.requeued' => 'enqueue.consumers.requeued',
+ 'metric.consumers.memoryUsage' => 'enqueue.consumers.memoryUsage',
+ ], $config);
+ }
+}
diff --git a/pkg/monitoring/GenericStatsStorageFactory.php b/pkg/monitoring/GenericStatsStorageFactory.php
new file mode 100644
index 000000000..55475f953
--- /dev/null
+++ b/pkg/monitoring/GenericStatsStorageFactory.php
@@ -0,0 +1,65 @@
+ $config];
+ }
+
+ if (false === \is_array($config)) {
+ throw new \InvalidArgumentException('The config must be either array or DSN string.');
+ }
+
+ if (false === array_key_exists('dsn', $config)) {
+ throw new \InvalidArgumentException('The config must have dsn key set.');
+ }
+
+ $dsn = Dsn::parseFirst($config['dsn']);
+
+ if ($storageClass = $this->findStorageClass($dsn, Resources::getKnownStorages())) {
+ return new $storageClass(1 === \count($config) ? $config['dsn'] : $config);
+ }
+
+ throw new \LogicException(sprintf('A given scheme "%s" is not supported.', $dsn->getScheme()));
+ }
+
+ private function findStorageClass(Dsn $dsn, array $factories): ?string
+ {
+ $protocol = $dsn->getSchemeProtocol();
+
+ if ($dsn->getSchemeExtensions()) {
+ foreach ($factories as $storageClass => $info) {
+ if (empty($info['supportedSchemeExtensions'])) {
+ continue;
+ }
+
+ if (false === \in_array($protocol, $info['schemes'], true)) {
+ continue;
+ }
+
+ $diff = array_diff($info['supportedSchemeExtensions'], $dsn->getSchemeExtensions());
+ if (empty($diff)) {
+ return $storageClass;
+ }
+ }
+ }
+
+ foreach ($factories as $storageClass => $info) {
+ if (false === \in_array($protocol, $info['schemes'], true)) {
+ continue;
+ }
+
+ return $storageClass;
+ }
+
+ return null;
+ }
+}
diff --git a/pkg/monitoring/InfluxDbStorage.php b/pkg/monitoring/InfluxDbStorage.php
new file mode 100644
index 000000000..e39cccfd2
--- /dev/null
+++ b/pkg/monitoring/InfluxDbStorage.php
@@ -0,0 +1,264 @@
+ 'influxdb://127.0.0.1:8086',
+ * 'host' => '127.0.0.1',
+ * 'port' => '8086',
+ * 'user' => '',
+ * 'password' => '',
+ * 'db' => 'enqueue',
+ * 'measurementSentMessages' => 'sent-messages',
+ * 'measurementConsumedMessages' => 'consumed-messages',
+ * 'measurementConsumers' => 'consumers',
+ * 'client' => null, # Client instance. Null by default.
+ * 'retentionPolicy' => null,
+ * ]
+ *
+ * or
+ *
+ * influxdb://127.0.0.1:8086?user=Jon&password=secret
+ *
+ * @param array|string|null $config
+ */
+ public function __construct($config = 'influxdb:')
+ {
+ if (false == class_exists(Client::class)) {
+ throw new \LogicException('Seems client library is not installed. Please install "influxdb/influxdb-php"');
+ }
+
+ if (empty($config)) {
+ $config = [];
+ } elseif (is_string($config)) {
+ $config = self::parseDsn($config);
+ } elseif (is_array($config)) {
+ $config = empty($config['dsn']) ? $config : self::parseDsn($config['dsn']);
+ } elseif ($config instanceof Client) {
+ // Passing Client instead of array config is deprecated because it prevents setting any configuration values
+ // and causes library to use defaults.
+ @trigger_error(
+ sprintf('Passing %s as %s argument is deprecated. Pass it as "client" array property or use createWithClient instead',
+ Client::class,
+ __METHOD__
+ ), \E_USER_DEPRECATED);
+ $this->client = $config;
+ $config = [];
+ } else {
+ throw new \LogicException('The config must be either an array of options, a DSN string or null');
+ }
+
+ $config = array_replace([
+ 'host' => '127.0.0.1',
+ 'port' => '8086',
+ 'user' => '',
+ 'password' => '',
+ 'db' => 'enqueue',
+ 'measurementSentMessages' => 'sent-messages',
+ 'measurementConsumedMessages' => 'consumed-messages',
+ 'measurementConsumers' => 'consumers',
+ 'client' => null,
+ 'retentionPolicy' => null,
+ ], $config);
+
+ if (null !== $config['client']) {
+ if (!$config['client'] instanceof Client) {
+ throw new \InvalidArgumentException(sprintf('%s configuration property is expected to be an instance of %s class. %s was passed instead.', 'client', Client::class, gettype($config['client'])));
+ }
+ $this->client = $config['client'];
+ }
+
+ $this->config = $config;
+ }
+
+ /**
+ * @param string $config
+ */
+ public static function createWithClient(Client $client, $config = 'influxdb:'): self
+ {
+ if (is_string($config)) {
+ $config = self::parseDsn($config);
+ }
+ $config['client'] = $client;
+
+ return new self($config);
+ }
+
+ public function pushConsumerStats(ConsumerStats $stats): void
+ {
+ $points = [];
+
+ foreach ($stats->getQueues() as $queue) {
+ $tags = [
+ 'queue' => $queue,
+ 'consumerId' => $stats->getConsumerId(),
+ ];
+
+ $values = [
+ 'startedAtMs' => $stats->getStartedAtMs(),
+ 'started' => $stats->isStarted(),
+ 'finished' => $stats->isFinished(),
+ 'failed' => $stats->isFailed(),
+ 'received' => $stats->getReceived(),
+ 'acknowledged' => $stats->getAcknowledged(),
+ 'rejected' => $stats->getRejected(),
+ 'requeued' => $stats->getRequeued(),
+ 'memoryUsage' => $stats->getMemoryUsage(),
+ 'systemLoad' => $stats->getSystemLoad(),
+ ];
+
+ if ($stats->getFinishedAtMs()) {
+ $values['finishedAtMs'] = $stats->getFinishedAtMs();
+ }
+
+ $points[] = new Point($this->config['measurementConsumers'], null, $tags, $values, $stats->getTimestampMs());
+ }
+
+ $this->doWrite($points);
+ }
+
+ public function pushConsumedMessageStats(ConsumedMessageStats $stats): void
+ {
+ $tags = [
+ 'queue' => $stats->getQueue(),
+ 'status' => $stats->getStatus(),
+ ];
+
+ $properties = $stats->getProperties();
+
+ if (false === empty($properties[Config::TOPIC])) {
+ $tags['topic'] = $properties[Config::TOPIC];
+ }
+
+ if (false === empty($properties[Config::COMMAND])) {
+ $tags['command'] = $properties[Config::COMMAND];
+ }
+
+ $values = [
+ 'receivedAt' => $stats->getReceivedAtMs(),
+ 'processedAt' => $stats->getTimestampMs(),
+ 'redelivered' => $stats->isRedelivered(),
+ ];
+
+ if (ConsumedMessageStats::STATUS_FAILED === $stats->getStatus()) {
+ $values['failed'] = 1;
+ }
+
+ $runtime = $stats->getTimestampMs() - $stats->getReceivedAtMs();
+
+ $points = [
+ new Point($this->config['measurementConsumedMessages'], $runtime, $tags, $values, $stats->getTimestampMs()),
+ ];
+
+ $this->doWrite($points);
+ }
+
+ public function pushSentMessageStats(SentMessageStats $stats): void
+ {
+ $tags = [
+ 'destination' => $stats->getDestination(),
+ ];
+
+ $properties = $stats->getProperties();
+
+ if (false === empty($properties[Config::TOPIC])) {
+ $tags['topic'] = $properties[Config::TOPIC];
+ }
+
+ if (false === empty($properties[Config::COMMAND])) {
+ $tags['command'] = $properties[Config::COMMAND];
+ }
+
+ $points = [
+ new Point($this->config['measurementSentMessages'], 1, $tags, [], $stats->getTimestampMs()),
+ ];
+
+ $this->doWrite($points);
+ }
+
+ private function doWrite(array $points): void
+ {
+ if (null === $this->client) {
+ $this->client = new Client(
+ $this->config['host'],
+ $this->config['port'],
+ $this->config['user'],
+ $this->config['password']
+ );
+ }
+
+ if ($this->client->getDriver() instanceof QueryDriverInterface) {
+ if (null === $this->database) {
+ $this->database = $this->client->selectDB($this->config['db']);
+ $this->database->create();
+ }
+
+ $this->database->writePoints($points, Database::PRECISION_MILLISECONDS, $this->config['retentionPolicy']);
+ } else {
+ // Code below mirrors what `writePoints` method of Database does.
+ try {
+ $parameters = [
+ 'url' => sprintf('write?db=%s&precision=%s', $this->config['db'], Database::PRECISION_MILLISECONDS),
+ 'database' => $this->config['db'],
+ 'method' => 'post',
+ ];
+ if (null !== $this->config['retentionPolicy']) {
+ $parameters['url'] .= sprintf('&rp=%s', $this->config['retentionPolicy']);
+ }
+
+ $this->client->write($parameters, $points);
+ } catch (\Exception $e) {
+ throw new InfluxDBException($e->getMessage(), $e->getCode());
+ }
+ }
+ }
+
+ private static function parseDsn(string $dsn): array
+ {
+ $dsn = Dsn::parseFirst($dsn);
+
+ if (false === in_array($dsn->getSchemeProtocol(), ['influxdb'], true)) {
+ throw new \LogicException(sprintf('The given scheme protocol "%s" is not supported. It must be "influxdb"', $dsn->getSchemeProtocol()));
+ }
+
+ return array_filter(array_replace($dsn->getQuery(), [
+ 'host' => $dsn->getHost(),
+ 'port' => $dsn->getPort(),
+ 'user' => $dsn->getUser(),
+ 'password' => $dsn->getPassword(),
+ 'db' => $dsn->getString('db'),
+ 'measurementSentMessages' => $dsn->getString('measurementSentMessages'),
+ 'measurementConsumedMessages' => $dsn->getString('measurementConsumedMessages'),
+ 'measurementConsumers' => $dsn->getString('measurementConsumers'),
+ 'retentionPolicy' => $dsn->getString('retentionPolicy'),
+ ]), function ($value) { return null !== $value; });
+ }
+}
diff --git a/pkg/monitoring/JsonSerializer.php b/pkg/monitoring/JsonSerializer.php
new file mode 100644
index 000000000..8d046092a
--- /dev/null
+++ b/pkg/monitoring/JsonSerializer.php
@@ -0,0 +1,31 @@
+ $rfClass->getShortName(),
+ ];
+
+ foreach ($rfClass->getProperties() as $rfProperty) {
+ $rfProperty->setAccessible(true);
+ $data[$rfProperty->getName()] = $rfProperty->getValue($stats);
+ $rfProperty->setAccessible(false);
+ }
+
+ $json = json_encode($data);
+
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
+ }
+
+ return $json;
+ }
+}
diff --git a/pkg/monitoring/LICENSE b/pkg/monitoring/LICENSE
new file mode 100644
index 000000000..7afbaa1ff
--- /dev/null
+++ b/pkg/monitoring/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+Copyright (c) 2018 Forma-Pro
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished
+to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/pkg/monitoring/README.md b/pkg/monitoring/README.md
new file mode 100644
index 000000000..70f27e3dd
--- /dev/null
+++ b/pkg/monitoring/README.md
@@ -0,0 +1,46 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
+# Enqueue Monitoring
+
+Queue Monitoring tool. Track sent, consumed messages. Consumers performances.
+
+* Could be used with any message queue library.
+* Could be integrated to any PHP framework
+* Could send stats to any analytical platform
+* Supports Datadog, InfluxDb, Grafana and WAMP out of the box.
+* Provides integration for Enqueue
+
+[](https://gitter.im/php-enqueue/Lobby)
+[](https://github.com/php-enqueue/monitoring/actions?query=workflow%3ACI)
+[](https://packagist.org/packages/enqueue/monitoring)
+[](https://packagist.org/packages/enqueue/monitoring)
+
+## Resources
+
+* [Site](https://enqueue.forma-pro.com/)
+* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/monitoring.md)
+* [Questions](https://gitter.im/php-enqueue/Lobby)
+* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
+
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
+
+Learn more at [forma-pro.com](https://forma-pro.com).
+
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
+
+## License
+
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/monitoring/Resources.php b/pkg/monitoring/Resources.php
new file mode 100644
index 000000000..409d9861f
--- /dev/null
+++ b/pkg/monitoring/Resources.php
@@ -0,0 +1,55 @@
+ $item) {
+ foreach ($item['schemes'] as $scheme) {
+ $schemes[$scheme] = $storageClass;
+ }
+ }
+
+ return $schemes;
+ }
+
+ public static function getKnownStorages(): array
+ {
+ if (null === self::$knownStorages) {
+ $map = [];
+
+ $map[WampStorage::class] = [
+ 'schemes' => ['wamp', 'ws'],
+ 'supportedSchemeExtensions' => [],
+ ];
+
+ $map[InfluxDbStorage::class] = [
+ 'schemes' => ['influxdb'],
+ 'supportedSchemeExtensions' => [],
+ ];
+
+ $map[DatadogStorage::class] = [
+ 'schemes' => ['datadog'],
+ 'supportedSchemeExtensions' => [],
+ ];
+
+ self::$knownStorages = $map;
+ }
+
+ return self::$knownStorages;
+ }
+}
diff --git a/pkg/monitoring/SentMessageStats.php b/pkg/monitoring/SentMessageStats.php
new file mode 100644
index 000000000..f8ddc73be
--- /dev/null
+++ b/pkg/monitoring/SentMessageStats.php
@@ -0,0 +1,96 @@
+timestampMs = $timestampMs;
+ $this->destination = $destination;
+ $this->isTopic = $isTopic;
+ $this->messageId = $messageId;
+ $this->correlationId = $correlationId;
+ $this->headers = $headers;
+ $this->properties = $properties;
+ }
+
+ public function getTimestampMs(): int
+ {
+ return $this->timestampMs;
+ }
+
+ public function getDestination(): string
+ {
+ return $this->destination;
+ }
+
+ public function isTopic(): bool
+ {
+ return $this->isTopic;
+ }
+
+ public function getMessageId(): ?string
+ {
+ return $this->messageId;
+ }
+
+ public function getCorrelationId(): ?string
+ {
+ return $this->correlationId;
+ }
+
+ public function getHeaders(): array
+ {
+ return $this->headers;
+ }
+
+ public function getProperties(): array
+ {
+ return $this->properties;
+ }
+}
diff --git a/pkg/monitoring/Serializer.php b/pkg/monitoring/Serializer.php
new file mode 100644
index 000000000..227dbc602
--- /dev/null
+++ b/pkg/monitoring/Serializer.php
@@ -0,0 +1,10 @@
+diUtils = DiUtils::create(self::MODULE, $name);
+ }
+
+ public static function getConfiguration(string $name = 'monitoring'): ArrayNodeDefinition
+ {
+ $builder = new ArrayNodeDefinition($name);
+
+ $builder
+ ->info(sprintf('The "%s" option could accept a string DSN, an array with DSN key, or null. It accept extra options. To find out what option you can set, look at stats storage constructor doc block.', $name))
+ ->beforeNormalization()
+ ->always(function ($v) {
+ if (\is_array($v)) {
+ if (isset($v['storage_factory_class'], $v['storage_factory_service'])) {
+ throw new \LogicException('Both options storage_factory_class and storage_factory_service are set. Please choose one.');
+ }
+
+ return $v;
+ }
+
+ if (is_string($v)) {
+ return ['dsn' => $v];
+ }
+
+ return $v;
+ })
+ ->end()
+ ->ignoreExtraKeys(false)
+ ->children()
+ ->scalarNode('dsn')
+ ->cannotBeEmpty()
+ ->isRequired()
+ ->info(sprintf('The stats storage DSN. These schemes are supported: "%s".', implode('", "', array_keys(Resources::getKnownSchemes()))))
+ ->end()
+ ->scalarNode('storage_factory_service')
+ ->info(sprintf('The factory class should implement "%s" interface', StatsStorageFactory::class))
+ ->end()
+ ->scalarNode('storage_factory_class')
+ ->info(sprintf('The factory service should be a class that implements "%s" interface', StatsStorageFactory::class))
+ ->end()
+ ->end()
+ ;
+
+ return $builder;
+ }
+
+ public function buildStorage(ContainerBuilder $container, array $config): void
+ {
+ $storageId = $this->diUtils->format('storage');
+ $storageFactoryId = $this->diUtils->format('storage.factory');
+
+ if (isset($config['storage_factory_service'])) {
+ $container->setAlias($storageFactoryId, $config['storage_factory_service']);
+ } elseif (isset($config['storage_factory_class'])) {
+ $container->register($storageFactoryId, $config['storage_factory_class']);
+ } else {
+ $container->register($storageFactoryId, GenericStatsStorageFactory::class);
+ }
+
+ unset($config['storage_factory_service'], $config['storage_factory_class']);
+
+ $container->register($storageId, StatsStorage::class)
+ ->setFactory([new Reference($storageFactoryId), 'create'])
+ ->addArgument($config)
+ ;
+ }
+
+ public function buildClientExtension(ContainerBuilder $container, array $config): void
+ {
+ $container->register($this->diUtils->format('client_extension'), ClientMonitoringExtension::class)
+ ->addArgument($this->diUtils->reference('storage'))
+ ->addArgument(new Reference('logger'))
+ ->addTag('enqueue.client_extension', ['client' => $this->diUtils->getConfigName()])
+ ;
+ }
+
+ public function buildConsumerExtension(ContainerBuilder $container, array $config): void
+ {
+ $container->register($this->diUtils->format('consumer_extension'), ConsumerMonitoringExtension::class)
+ ->addArgument($this->diUtils->reference('storage'))
+ ->addTag('enqueue.consumption_extension', ['client' => $this->diUtils->getConfigName()])
+ ->addTag('enqueue.transport.consumption_extension', ['transport' => $this->diUtils->getConfigName()])
+ ;
+ }
+}
diff --git a/pkg/monitoring/Tests/GenericStatsStorageFactoryTest.php b/pkg/monitoring/Tests/GenericStatsStorageFactoryTest.php
new file mode 100644
index 000000000..fe7c2c759
--- /dev/null
+++ b/pkg/monitoring/Tests/GenericStatsStorageFactoryTest.php
@@ -0,0 +1,52 @@
+assertClassImplements(StatsStorageFactory::class, GenericStatsStorageFactory::class);
+ }
+
+ public function testShouldCreateInfluxDbStorage(): void
+ {
+ $storage = (new GenericStatsStorageFactory())->create('influxdb:');
+
+ $this->assertInstanceOf(InfluxDbStorage::class, $storage);
+ }
+
+ public function testShouldCreateWampStorage(): void
+ {
+ $storage = (new GenericStatsStorageFactory())->create('wamp:');
+
+ $this->assertInstanceOf(WampStorage::class, $storage);
+ }
+
+ public function testShouldCreateDatadogStorage(): void
+ {
+ $storage = (new GenericStatsStorageFactory())->create('datadog:');
+
+ $this->assertInstanceOf(DatadogStorage::class, $storage);
+ }
+
+ public function testShouldThrowIfStorageIsNotSupported(): void
+ {
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('A given scheme "unsupported" is not supported.');
+
+ (new GenericStatsStorageFactory())->create('unsupported:');
+ }
+}
diff --git a/pkg/monitoring/WampStorage.php b/pkg/monitoring/WampStorage.php
new file mode 100644
index 000000000..0d5ba1801
--- /dev/null
+++ b/pkg/monitoring/WampStorage.php
@@ -0,0 +1,211 @@
+ 'wamp://127.0.0.1:9090',
+ * 'host' => '127.0.0.1',
+ * 'port' => '9090',
+ * 'topic' => 'stats',
+ * 'max_retries' => 15,
+ * 'initial_retry_delay' => 1.5,
+ * 'max_retry_delay' => 300,
+ * 'retry_delay_growth' => 1.5,
+ * ]
+ *
+ * or
+ *
+ * wamp://127.0.0.1:9090?max_retries=10
+ *
+ * @param array|string|null $config
+ */
+ public function __construct($config = 'wamp:')
+ {
+ if (false == class_exists(Client::class) || false == class_exists(PawlTransportProvider::class)) {
+ throw new \LogicException('Seems client libraries are not installed. Please install "thruway/client" and "thruway/pawl-transport"');
+ }
+
+ if (empty($config)) {
+ $config = $this->parseDsn('wamp:');
+ } elseif (is_string($config)) {
+ $config = $this->parseDsn($config);
+ } elseif (is_array($config)) {
+ $config = empty($config['dsn']) ? $config : $this->parseDsn($config['dsn']);
+ } else {
+ throw new \LogicException('The config must be either an array of options, a DSN string or null');
+ }
+
+ $config = array_replace([
+ 'host' => '127.0.0.1',
+ 'port' => '9090',
+ 'topic' => 'stats',
+ 'max_retries' => 15,
+ 'initial_retry_delay' => 1.5,
+ 'max_retry_delay' => 300,
+ 'retry_delay_growth' => 1.5,
+ ], $config);
+
+ $this->config = $config;
+
+ $this->serialiser = new JsonSerializer();
+ }
+
+ public function pushConsumerStats(ConsumerStats $stats): void
+ {
+ $this->push($stats);
+ }
+
+ public function pushConsumedMessageStats(ConsumedMessageStats $stats): void
+ {
+ $this->push($stats);
+ }
+
+ public function pushSentMessageStats(SentMessageStats $stats): void
+ {
+ $this->push($stats);
+ }
+
+ private function push(Stats $stats)
+ {
+ $init = false;
+ $this->stats = $stats;
+
+ if (null === $this->client) {
+ $init = true;
+
+ $this->client = $this->createClient();
+ $this->client->setAttemptRetry(true);
+ $this->client->on('open', function (ClientSession $session) {
+ $this->session = $session;
+
+ $this->doSendMessageIfPossible();
+ });
+
+ $this->client->on('close', function () {
+ if ($this->session === $this->client->getSession()) {
+ $this->session = null;
+ }
+ });
+
+ $this->client->on('error', function () {
+ if ($this->session === $this->client->getSession()) {
+ $this->session = null;
+ }
+ });
+
+ $this->client->on('do-send', function (Stats $stats) {
+ $onFinish = function () {
+ $this->client->emit('do-stop');
+ };
+
+ $payload = $this->serialiser->toString($stats);
+
+ $this->session->publish('stats', [$payload], [], ['acknowledge' => true])
+ ->then($onFinish, $onFinish);
+ });
+
+ $this->client->on('do-stop', function () {
+ $this->client->getLoop()->stop();
+ });
+ }
+
+ $this->client->getLoop()->futureTick(function () {
+ $this->doSendMessageIfPossible();
+ });
+
+ if ($init) {
+ $this->client->start(false);
+ }
+
+ $this->client->getLoop()->run();
+ }
+
+ private function doSendMessageIfPossible()
+ {
+ if (null === $this->session) {
+ return;
+ }
+
+ if (null === $this->stats) {
+ return;
+ }
+
+ $stats = $this->stats;
+
+ $this->stats = null;
+
+ $this->client->emit('do-send', [$stats]);
+ }
+
+ private function createClient(): Client
+ {
+ $uri = sprintf('ws://%s:%s', $this->config['host'], $this->config['port']);
+
+ $client = new Client('realm1');
+ $client->addTransportProvider(new PawlTransportProvider($uri));
+ $client->setReconnectOptions([
+ 'max_retries' => $this->config['max_retries'],
+ 'initial_retry_delay' => $this->config['initial_retry_delay'],
+ 'max_retry_delay' => $this->config['max_retry_delay'],
+ 'retry_delay_growth' => $this->config['retry_delay_growth'],
+ ]);
+
+ return $client;
+ }
+
+ private function parseDsn(string $dsn): array
+ {
+ $dsn = Dsn::parseFirst($dsn);
+
+ if (false === in_array($dsn->getSchemeProtocol(), ['wamp', 'ws'], true)) {
+ throw new \LogicException(sprintf('The given scheme protocol "%s" is not supported. It must be "wamp"', $dsn->getSchemeProtocol()));
+ }
+
+ return array_filter(array_replace($dsn->getQuery(), [
+ 'host' => $dsn->getHost(),
+ 'port' => $dsn->getPort(),
+ 'topic' => $dsn->getString('topic'),
+ 'max_retries' => $dsn->getDecimal('max_retries'),
+ 'initial_retry_delay' => $dsn->getFloat('initial_retry_delay'),
+ 'max_retry_delay' => $dsn->getDecimal('max_retry_delay'),
+ 'retry_delay_growth' => $dsn->getFloat('retry_delay_growth'),
+ ]), function ($value) { return null !== $value; });
+ }
+}
diff --git a/pkg/monitoring/composer.json b/pkg/monitoring/composer.json
new file mode 100644
index 000000000..9dc9e3c6c
--- /dev/null
+++ b/pkg/monitoring/composer.json
@@ -0,0 +1,49 @@
+{
+ "name": "enqueue/monitoring",
+ "type": "library",
+ "description": "Enqueue Monitoring",
+ "keywords": ["messaging", "queue", "monitoring", "grafana"],
+ "homepage": "https://enqueue.forma-pro.com/",
+ "license": "MIT",
+ "require": {
+ "php": "^8.1",
+ "enqueue/enqueue": "^0.10",
+ "enqueue/dsn": "^0.10"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^9.5",
+ "enqueue/test": "0.10.x-dev",
+ "influxdb/influxdb-php": "^1.14",
+ "datadog/php-datadogstatsd": "^1.3",
+ "thruway/client": "^0.5.5",
+ "thruway/pawl-transport": "^0.5.2",
+ "voryx/thruway-common": "^1.0.1",
+ "ratchet/pawl": "^0.4.3",
+ "ratchet/rfc6455": "^0.4.0"
+ },
+ "suggest": {
+ "thruway/client": "Client for Thruway and the WAMP (Web Application Messaging Protocol).",
+ "thruway/pawl-transport": "Pawl WebSocket Transport for Thruway Client",
+ "influxdb/influxdb-php": "A PHP Client for InfluxDB, a time series database",
+ "datadog/php-datadogstatsd": "Datadog monitoring tool PHP integration"
+ },
+ "support": {
+ "email": "opensource@forma-pro.com",
+ "issues": "https://github.com/php-enqueue/enqueue-dev/issues",
+ "forum": "https://gitter.im/php-enqueue/Lobby",
+ "source": "https://github.com/php-enqueue/enqueue-dev",
+ "docs": "https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md"
+ },
+ "autoload": {
+ "psr-4": { "Enqueue\\Monitoring\\": "" },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "minimum-stability": "dev",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "0.10.x-dev"
+ }
+ }
+}
diff --git a/pkg/monitoring/phpunit.xml.dist b/pkg/monitoring/phpunit.xml.dist
new file mode 100644
index 000000000..254ab22d6
--- /dev/null
+++ b/pkg/monitoring/phpunit.xml.dist
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+ ./Tests
+
+
+
+
+
+ .
+
+ ./vendor
+ ./Tests
+
+
+
+
diff --git a/pkg/null/.gitattributes b/pkg/null/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/null/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/null/.github/workflows/ci.yml b/pkg/null/.github/workflows/ci.yml
new file mode 100644
index 000000000..c91cb39ab
--- /dev/null
+++ b/pkg/null/.github/workflows/ci.yml
@@ -0,0 +1,29 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/null/.travis.yml b/pkg/null/.travis.yml
deleted file mode 100644
index 9ed4fa123..000000000
--- a/pkg/null/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-sudo: false
-
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
- - '7.2'
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - composer self-update
- - composer install --prefer-source
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/null/NullMessage.php b/pkg/null/NullMessage.php
index bd48a387e..93fc57c3d 100644
--- a/pkg/null/NullMessage.php
+++ b/pkg/null/NullMessage.php
@@ -97,7 +97,7 @@ public function setRedelivered(bool $redelivered): void
$this->redelivered = $redelivered;
}
- public function setCorrelationId(string $correlationId = null): void
+ public function setCorrelationId(?string $correlationId = null): void
{
$headers = $this->getHeaders();
$headers['correlation_id'] = (string) $correlationId;
@@ -110,7 +110,7 @@ public function getCorrelationId(): ?string
return $this->getHeader('correlation_id');
}
- public function setMessageId(string $messageId = null): void
+ public function setMessageId(?string $messageId = null): void
{
$headers = $this->getHeaders();
$headers['message_id'] = (string) $messageId;
@@ -130,7 +130,7 @@ public function getTimestamp(): ?int
return null === $value ? null : (int) $value;
}
- public function setTimestamp(int $timestamp = null): void
+ public function setTimestamp(?int $timestamp = null): void
{
$headers = $this->getHeaders();
$headers['timestamp'] = (int) $timestamp;
@@ -138,7 +138,7 @@ public function setTimestamp(int $timestamp = null): void
$this->setHeaders($headers);
}
- public function setReplyTo(string $replyTo = null): void
+ public function setReplyTo(?string $replyTo = null): void
{
$this->setHeader('reply_to', $replyTo);
}
diff --git a/pkg/null/NullProducer.php b/pkg/null/NullProducer.php
index 47235e7f6..1349de9ba 100644
--- a/pkg/null/NullProducer.php
+++ b/pkg/null/NullProducer.php
@@ -23,7 +23,7 @@ public function send(Destination $destination, Message $message): void
/**
* @return NullProducer
*/
- public function setDeliveryDelay(int $deliveryDelay = null): Producer
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
{
$this->deliveryDelay = $deliveryDelay;
@@ -38,7 +38,7 @@ public function getDeliveryDelay(): ?int
/**
* @return NullProducer
*/
- public function setPriority(int $priority = null): Producer
+ public function setPriority(?int $priority = null): Producer
{
$this->priority = $priority;
@@ -53,7 +53,7 @@ public function getPriority(): ?int
/**
* @return NullProducer
*/
- public function setTimeToLive(int $timeToLive = null): Producer
+ public function setTimeToLive(?int $timeToLive = null): Producer
{
$this->timeToLive = $timeToLive;
diff --git a/pkg/null/README.md b/pkg/null/README.md
index 14f7a0384..48c16eaf0 100644
--- a/pkg/null/README.md
+++ b/pkg/null/README.md
@@ -1,26 +1,39 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Enqueue Null Transport
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/null)
+[](https://github.com/php-enqueue/null/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/null)
[](https://packagist.org/packages/enqueue/null)
-
+
This is an implementation of Queue Interop specification. It does not send messages any where and could be used as mock. Suitable in tests.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/transport/null/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
diff --git a/pkg/null/Tests/NullConnectionFactoryTest.php b/pkg/null/Tests/NullConnectionFactoryTest.php
index 80cfcc904..bbf377e85 100644
--- a/pkg/null/Tests/NullConnectionFactoryTest.php
+++ b/pkg/null/Tests/NullConnectionFactoryTest.php
@@ -17,11 +17,6 @@ public function testShouldImplementConnectionFactoryInterface()
$this->assertClassImplements(ConnectionFactory::class, NullConnectionFactory::class);
}
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new NullConnectionFactory();
- }
-
public function testShouldReturnNullContextOnCreateContextCall()
{
$factory = new NullConnectionFactory();
diff --git a/pkg/null/Tests/NullConsumerTest.php b/pkg/null/Tests/NullConsumerTest.php
index 6419e9c39..f4de53311 100644
--- a/pkg/null/Tests/NullConsumerTest.php
+++ b/pkg/null/Tests/NullConsumerTest.php
@@ -18,11 +18,6 @@ public function testShouldImplementMessageConsumerInterface()
$this->assertClassImplements(Consumer::class, NullConsumer::class);
}
- public function testCouldBeConstructedWithQueueAsArgument()
- {
- new NullConsumer(new NullQueue('aName'));
- }
-
public function testShouldAlwaysReturnNullOnReceive()
{
$consumer = new NullConsumer(new NullQueue('theQueueName'));
@@ -41,6 +36,9 @@ public function testShouldAlwaysReturnNullOnReceiveNoWait()
$this->assertNull($consumer->receiveNoWait());
}
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldDoNothingOnAcknowledge()
{
$consumer = new NullConsumer(new NullQueue('theQueueName'));
@@ -48,6 +46,9 @@ public function testShouldDoNothingOnAcknowledge()
$consumer->acknowledge(new NullMessage());
}
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldDoNothingOnReject()
{
$consumer = new NullConsumer(new NullQueue('theQueueName'));
diff --git a/pkg/null/Tests/NullContextTest.php b/pkg/null/Tests/NullContextTest.php
index 4e5150990..f0da566d2 100644
--- a/pkg/null/Tests/NullContextTest.php
+++ b/pkg/null/Tests/NullContextTest.php
@@ -21,11 +21,6 @@ public function testShouldImplementSessionInterface()
$this->assertClassImplements(Context::class, NullContext::class);
}
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new NullContext();
- }
-
public function testShouldAllowCreateMessageWithoutAnyArguments()
{
$context = new NullContext();
diff --git a/pkg/null/Tests/NullProducerTest.php b/pkg/null/Tests/NullProducerTest.php
index 289dab6c0..140d683ba 100644
--- a/pkg/null/Tests/NullProducerTest.php
+++ b/pkg/null/Tests/NullProducerTest.php
@@ -18,11 +18,9 @@ public function testShouldImplementProducerInterface()
$this->assertClassImplements(Producer::class, NullProducer::class);
}
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new NullProducer();
- }
-
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldDoNothingOnSend()
{
$producer = new NullProducer();
diff --git a/pkg/null/Tests/NullQueueTest.php b/pkg/null/Tests/NullQueueTest.php
index 0dfaf2f28..cb29ca180 100644
--- a/pkg/null/Tests/NullQueueTest.php
+++ b/pkg/null/Tests/NullQueueTest.php
@@ -16,11 +16,6 @@ public function testShouldImplementQueueInterface()
$this->assertClassImplements(Queue::class, NullQueue::class);
}
- public function testCouldBeConstructedWithNameAsArgument()
- {
- new NullQueue('aName');
- }
-
public function testShouldAllowGetNameSetInConstructor()
{
$queue = new NullQueue('theName');
diff --git a/pkg/null/Tests/NullTopicTest.php b/pkg/null/Tests/NullTopicTest.php
index a40545120..27c4b58de 100644
--- a/pkg/null/Tests/NullTopicTest.php
+++ b/pkg/null/Tests/NullTopicTest.php
@@ -16,11 +16,6 @@ public function testShouldImplementTopicInterface()
$this->assertClassImplements(Topic::class, NullTopic::class);
}
- public function testCouldBeConstructedWithNameAsArgument()
- {
- new NullTopic('aName');
- }
-
public function testShouldAllowGetNameSetInConstructor()
{
$topic = new NullTopic('theName');
diff --git a/pkg/null/Tests/Spec/NullMessageTest.php b/pkg/null/Tests/Spec/NullMessageTest.php
index 34c6863ed..6bacc9294 100644
--- a/pkg/null/Tests/Spec/NullMessageTest.php
+++ b/pkg/null/Tests/Spec/NullMessageTest.php
@@ -7,9 +7,6 @@
class NullMessageTest extends MessageSpec
{
- /**
- * {@inheritdoc}
- */
protected function createMessage()
{
return new NullMessage();
diff --git a/pkg/null/composer.json b/pkg/null/composer.json
index e17435633..a09910a47 100644
--- a/pkg/null/composer.json
+++ b/pkg/null/composer.json
@@ -6,13 +6,13 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "queue-interop/queue-interop": "0.7.x-dev"
+ "php": "^8.1",
+ "queue-interop/queue-interop": "^0.8"
},
"require-dev": {
- "phpunit/phpunit": "~5.5",
- "enqueue/test": "0.9.x-dev",
- "queue-interop/queue-spec": "0.6.x-dev"
+ "phpunit/phpunit": "^9.5",
+ "enqueue/test": "0.10.x-dev",
+ "queue-interop/queue-spec": "^0.6.2"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -30,7 +30,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/null/phpunit.xml.dist b/pkg/null/phpunit.xml.dist
index 2fd4e20c3..07729246d 100644
--- a/pkg/null/phpunit.xml.dist
+++ b/pkg/null/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/pheanstalk/.gitattributes b/pkg/pheanstalk/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/pheanstalk/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/pheanstalk/.github/workflows/ci.yml b/pkg/pheanstalk/.github/workflows/ci.yml
new file mode 100644
index 000000000..c91cb39ab
--- /dev/null
+++ b/pkg/pheanstalk/.github/workflows/ci.yml
@@ -0,0 +1,29 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/pheanstalk/.travis.yml b/pkg/pheanstalk/.travis.yml
deleted file mode 100644
index 9ed4fa123..000000000
--- a/pkg/pheanstalk/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-sudo: false
-
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
- - '7.2'
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - composer self-update
- - composer install --prefer-source
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/pheanstalk/PheanstalkConsumer.php b/pkg/pheanstalk/PheanstalkConsumer.php
index 337b77d9d..3fb217683 100644
--- a/pkg/pheanstalk/PheanstalkConsumer.php
+++ b/pkg/pheanstalk/PheanstalkConsumer.php
@@ -88,11 +88,20 @@ public function acknowledge(Message $message): void
*/
public function reject(Message $message, bool $requeue = false): void
{
- $this->acknowledge($message);
+ InvalidMessageException::assertMessageInstanceOf($message, PheanstalkMessage::class);
+
+ if (false == $message->getJob()) {
+ $state = $requeue ? 'requeued' : 'rejected';
+ throw new \LogicException(sprintf('The message could not be %s because it does not have job set.', $state));
+ }
if ($requeue) {
$this->pheanstalk->release($message->getJob(), $message->getPriority(), $message->getDelay());
+
+ return;
}
+
+ $this->acknowledge($message);
}
private function convertJobToMessage(Job $job): PheanstalkMessage
@@ -100,7 +109,9 @@ private function convertJobToMessage(Job $job): PheanstalkMessage
$stats = $this->pheanstalk->statsJob($job);
$message = PheanstalkMessage::jsonUnserialize($job->getData());
- $message->setRedelivered($stats['reserves'] > 1);
+ if (isset($stats['reserves'])) {
+ $message->setRedelivered($stats['reserves'] > 1);
+ }
$message->setJob($job);
return $message;
diff --git a/pkg/pheanstalk/PheanstalkMessage.php b/pkg/pheanstalk/PheanstalkMessage.php
index cf4ea1905..5bff1a7a6 100644
--- a/pkg/pheanstalk/PheanstalkMessage.php
+++ b/pkg/pheanstalk/PheanstalkMessage.php
@@ -103,7 +103,7 @@ public function setRedelivered(bool $redelivered): void
$this->redelivered = $redelivered;
}
- public function setCorrelationId(string $correlationId = null): void
+ public function setCorrelationId(?string $correlationId = null): void
{
$this->setHeader('correlation_id', (string) $correlationId);
}
@@ -113,7 +113,7 @@ public function getCorrelationId(): ?string
return $this->getHeader('correlation_id');
}
- public function setMessageId(string $messageId = null): void
+ public function setMessageId(?string $messageId = null): void
{
$this->setHeader('message_id', (string) $messageId);
}
@@ -130,12 +130,12 @@ public function getTimestamp(): ?int
return null === $value ? null : (int) $value;
}
- public function setTimestamp(int $timestamp = null): void
+ public function setTimestamp(?int $timestamp = null): void
{
$this->setHeader('timestamp', $timestamp);
}
- public function setReplyTo(string $replyTo = null): void
+ public function setReplyTo(?string $replyTo = null): void
{
$this->setHeader('reply_to', $replyTo);
}
@@ -187,12 +187,8 @@ public function jsonSerialize(): array
public static function jsonUnserialize(string $json): self
{
$data = json_decode($json, true);
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'The malformed json given. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
}
return new self($data['body'], $data['properties'], $data['headers']);
@@ -203,7 +199,7 @@ public function getJob(): ?Job
return $this->job;
}
- public function setJob(Job $job = null): void
+ public function setJob(?Job $job = null): void
{
$this->job = $job;
}
diff --git a/pkg/pheanstalk/PheanstalkProducer.php b/pkg/pheanstalk/PheanstalkProducer.php
index e0d538043..0c8ffd8ff 100644
--- a/pkg/pheanstalk/PheanstalkProducer.php
+++ b/pkg/pheanstalk/PheanstalkProducer.php
@@ -18,6 +18,21 @@ class PheanstalkProducer implements Producer
*/
private $pheanstalk;
+ /**
+ * @var int
+ */
+ private $deliveryDelay;
+
+ /**
+ * @var int
+ */
+ private $priority;
+
+ /**
+ * @var int
+ */
+ private $timeToLive;
+
public function __construct(Pheanstalk $pheanstalk)
{
$this->pheanstalk = $pheanstalk;
@@ -33,12 +48,18 @@ public function send(Destination $destination, Message $message): void
InvalidMessageException::assertMessageInstanceOf($message, PheanstalkMessage::class);
$rawMessage = json_encode($message);
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'Could not encode value into json. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('Could not encode value into json. Error %s and message %s', json_last_error(), json_last_error_msg()));
+ }
+
+ if (null !== $this->priority && null === $message->getHeader('priority')) {
+ $message->setPriority($this->priority);
+ }
+ if (null !== $this->deliveryDelay && null === $message->getHeader('delay')) {
+ $message->setDelay($this->deliveryDelay / 1000);
+ }
+ if (null !== $this->timeToLive && null === $message->getHeader('ttr')) {
+ $message->setTimeToRun($this->timeToLive / 1000);
}
$this->pheanstalk->useTube($destination->getName())->put(
@@ -52,51 +73,45 @@ public function send(Destination $destination, Message $message): void
/**
* @return PheanstalkProducer
*/
- public function setDeliveryDelay(int $deliveryDelay = null): Producer
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
{
- if (null === $deliveryDelay) {
- return $this;
- }
+ $this->deliveryDelay = $deliveryDelay;
- throw new \LogicException('Not implemented');
+ return $this;
}
public function getDeliveryDelay(): ?int
{
- return null;
+ return $this->deliveryDelay;
}
/**
* @return PheanstalkProducer
*/
- public function setPriority(int $priority = null): Producer
+ public function setPriority(?int $priority = null): Producer
{
- if (null === $priority) {
- return $this;
- }
+ $this->priority = $priority;
- throw new \LogicException('Not implemented');
+ return $this;
}
public function getPriority(): ?int
{
- return null;
+ return $this->priority;
}
/**
* @return PheanstalkProducer
*/
- public function setTimeToLive(int $timeToLive = null): Producer
+ public function setTimeToLive(?int $timeToLive = null): Producer
{
- if (null === $timeToLive) {
- return $this;
- }
+ $this->timeToLive = $timeToLive;
- throw new \LogicException('Not implemented');
+ return $this;
}
public function getTimeToLive(): ?int
{
- return null;
+ return $this->timeToLive;
}
}
diff --git a/pkg/pheanstalk/README.md b/pkg/pheanstalk/README.md
index c1941485f..b6655ec8e 100644
--- a/pkg/pheanstalk/README.md
+++ b/pkg/pheanstalk/README.md
@@ -1,27 +1,40 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Beanstalk Transport
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/pheanstalk)
+[](https://github.com/php-enqueue/pheanstalk/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/pheanstalk)
[](https://packagist.org/packages/enqueue/pheanstalk)
-
-This is an implementation of the queue specification. It allows you to send and consume message from Beanstalkd broker.
+
+This is an implementation of the queue specification. It allows you to send and consume message from Beanstalkd broker.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/transport/pheanstalk/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
-It is released under the [MIT License](LICENSE).
\ No newline at end of file
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/pheanstalk/Tests/PheanstalkConnectionFactoryConfigTest.php b/pkg/pheanstalk/Tests/PheanstalkConnectionFactoryConfigTest.php
index 231ec0d77..a7bc7fc34 100644
--- a/pkg/pheanstalk/Tests/PheanstalkConnectionFactoryConfigTest.php
+++ b/pkg/pheanstalk/Tests/PheanstalkConnectionFactoryConfigTest.php
@@ -4,6 +4,7 @@
use Enqueue\Pheanstalk\PheanstalkConnectionFactory;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use PHPUnit\Framework\TestCase;
/**
@@ -12,6 +13,7 @@
class PheanstalkConnectionFactoryConfigTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testThrowNeitherArrayStringNorNullGivenAsConfig()
{
@@ -39,9 +41,6 @@ public function testThrowIfDsnCouldNotBeParsed()
/**
* @dataProvider provideConfigs
- *
- * @param mixed $config
- * @param mixed $expectedConfig
*/
public function testShouldParseConfigurationAsExpected($config, $expectedConfig)
{
diff --git a/pkg/pheanstalk/Tests/PheanstalkConsumerTest.php b/pkg/pheanstalk/Tests/PheanstalkConsumerTest.php
index 60015dc99..c79b20bbd 100644
--- a/pkg/pheanstalk/Tests/PheanstalkConsumerTest.php
+++ b/pkg/pheanstalk/Tests/PheanstalkConsumerTest.php
@@ -14,14 +14,6 @@ class PheanstalkConsumerTest extends TestCase
{
use ClassExtensionTrait;
- public function testCouldBeConstructedWithDestinationAndPheanstalkAsArguments()
- {
- new PheanstalkConsumer(
- new PheanstalkDestination('aQueueName'),
- $this->createPheanstalkMock()
- );
- }
-
public function testShouldReturnQueueSetInConstructor()
{
$destination = new PheanstalkDestination('aQueueName');
@@ -54,7 +46,7 @@ public function testShouldReceiveFromQueueAndReturnNullIfNoMessageInQueue()
public function testShouldReceiveFromQueueAndReturnMessageIfMessageInQueue()
{
$destination = new PheanstalkDestination('theQueueName');
- $message = new PheanstalkMessage('theBody', ['foo' => 'fooVal'], ['bar' => 'barVal']);
+ $message = new PheanstalkMessage('theBody', ['foo' => 'fooVal'], ['bar' => 'barVal']);
$job = new Job('theJobId', json_encode($message));
@@ -96,7 +88,7 @@ public function testShouldReceiveNoWaitFromQueueAndReturnNullIfNoMessageInQueue(
public function testShouldReceiveNoWaitFromQueueAndReturnMessageIfMessageInQueue()
{
$destination = new PheanstalkDestination('theQueueName');
- $message = new PheanstalkMessage('theBody', ['foo' => 'fooVal'], ['bar' => 'barVal']);
+ $message = new PheanstalkMessage('theBody', ['foo' => 'fooVal'], ['bar' => 'barVal']);
$job = new Job('theJobId', json_encode($message));
@@ -118,8 +110,111 @@ public function testShouldReceiveNoWaitFromQueueAndReturnMessageIfMessageInQueue
$this->assertSame($job, $actualMessage->getJob());
}
+ public function testShouldAcknowledgeMessage()
+ {
+ $destination = new PheanstalkDestination('theQueueName');
+ $message = new PheanstalkMessage();
+
+ $job = new Job('theJobId', json_encode($message));
+ $message->setJob($job);
+
+ $pheanstalk = $this->createPheanstalkMock();
+ $pheanstalk
+ ->expects($this->once())
+ ->method('delete')
+ ->with($job)
+ ;
+
+ $consumer = new PheanstalkConsumer($destination, $pheanstalk);
+
+ $consumer->acknowledge($message);
+ }
+
+ public function testAcknowledgeShouldThrowExceptionIfMessageHasNoJob()
+ {
+ $destination = new PheanstalkDestination('theQueueName');
+ $pheanstalk = $this->createPheanstalkMock();
+
+ $consumer = new PheanstalkConsumer($destination, $pheanstalk);
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The message could not be acknowledged because it does not have job set.');
+
+ $consumer->acknowledge(new PheanstalkMessage());
+ }
+
+ public function testShouldRejectMessage()
+ {
+ $destination = new PheanstalkDestination('theQueueName');
+ $message = new PheanstalkMessage();
+
+ $job = new Job('theJobId', json_encode($message));
+ $message->setJob($job);
+
+ $pheanstalk = $this->createPheanstalkMock();
+ $pheanstalk
+ ->expects($this->once())
+ ->method('delete')
+ ->with($job)
+ ;
+
+ $consumer = new PheanstalkConsumer($destination, $pheanstalk);
+
+ $consumer->reject($message);
+ }
+
+ public function testRejectShouldThrowExceptionIfMessageHasNoJob()
+ {
+ $destination = new PheanstalkDestination('theQueueName');
+ $pheanstalk = $this->createPheanstalkMock();
+
+ $consumer = new PheanstalkConsumer($destination, $pheanstalk);
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The message could not be rejected because it does not have job set.');
+
+ $consumer->reject(new PheanstalkMessage());
+ }
+
+ public function testShouldRequeueMessage()
+ {
+ $destination = new PheanstalkDestination('theQueueName');
+ $message = new PheanstalkMessage();
+
+ $job = new Job('theJobId', json_encode($message));
+ $message->setJob($job);
+
+ $pheanstalk = $this->createPheanstalkMock();
+ $pheanstalk
+ ->expects($this->once())
+ ->method('release')
+ ->with($job, Pheanstalk::DEFAULT_PRIORITY, Pheanstalk::DEFAULT_DELAY)
+ ;
+ $pheanstalk
+ ->expects($this->never())
+ ->method('delete')
+ ;
+
+ $consumer = new PheanstalkConsumer($destination, $pheanstalk);
+
+ $consumer->reject($message, true);
+ }
+
+ public function testRequeueShouldThrowExceptionIfMessageHasNoJob()
+ {
+ $destination = new PheanstalkDestination('theQueueName');
+ $pheanstalk = $this->createPheanstalkMock();
+
+ $consumer = new PheanstalkConsumer($destination, $pheanstalk);
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The message could not be requeued because it does not have job set.');
+
+ $consumer->reject(new PheanstalkMessage(), true);
+ }
+
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Pheanstalk
+ * @return \PHPUnit\Framework\MockObject\MockObject|Pheanstalk
*/
private function createPheanstalkMock()
{
diff --git a/pkg/pheanstalk/Tests/PheanstalkContextTest.php b/pkg/pheanstalk/Tests/PheanstalkContextTest.php
index fb92b6a72..3b7bfbeb7 100644
--- a/pkg/pheanstalk/Tests/PheanstalkContextTest.php
+++ b/pkg/pheanstalk/Tests/PheanstalkContextTest.php
@@ -21,11 +21,6 @@ public function testShouldImplementContextInterface()
$this->assertClassImplements(Context::class, PheanstalkContext::class);
}
- public function testCouldBeConstructedWithPheanstalkAsFirstArgument()
- {
- new PheanstalkContext($this->createPheanstalkMock());
- }
-
public function testThrowNotImplementedOnCreateTemporaryQueue()
{
$context = new PheanstalkContext($this->createPheanstalkMock());
@@ -73,7 +68,7 @@ public function testShouldDoConnectionDisconnectOnContextClose()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Pheanstalk
+ * @return \PHPUnit\Framework\MockObject\MockObject|Pheanstalk
*/
private function createPheanstalkMock()
{
diff --git a/pkg/pheanstalk/Tests/PheanstalkProducerTest.php b/pkg/pheanstalk/Tests/PheanstalkProducerTest.php
index 7a8d0b483..b9a69176c 100644
--- a/pkg/pheanstalk/Tests/PheanstalkProducerTest.php
+++ b/pkg/pheanstalk/Tests/PheanstalkProducerTest.php
@@ -11,17 +11,13 @@
use Interop\Queue\Exception\InvalidDestinationException;
use Interop\Queue\Exception\InvalidMessageException;
use Pheanstalk\Pheanstalk;
+use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class PheanstalkProducerTest extends TestCase
{
use ClassExtensionTrait;
- public function testCouldBeConstructedWithPheanstalkAsFirstArgument()
- {
- new PheanstalkProducer($this->createPheanstalkMock());
- }
-
public function testThrowIfDestinationInvalid()
{
$producer = new PheanstalkProducer($this->createPheanstalkMock());
@@ -65,8 +61,157 @@ public function testShouldJsonEncodeMessageAndPutToExpectedTube()
);
}
+ public function testMessagePriorityPrecedesPriority()
+ {
+ $message = new PheanstalkMessage('theBody');
+ $message->setPriority(100);
+
+ $pheanstalk = $this->createPheanstalkMock();
+ $pheanstalk
+ ->expects($this->once())
+ ->method('useTube')
+ ->with('theQueueName')
+ ->willReturnSelf()
+ ;
+ $pheanstalk
+ ->expects($this->once())
+ ->method('put')
+ ->with('{"body":"theBody","properties":[],"headers":{"priority":100}}', 100, Pheanstalk::DEFAULT_DELAY, Pheanstalk::DEFAULT_TTR)
+ ;
+
+ $producer = new PheanstalkProducer($pheanstalk);
+ $producer->setPriority(50);
+
+ $producer->send(
+ new PheanstalkDestination('theQueueName'),
+ $message
+ );
+ }
+
+ public function testAccessDeliveryDelayAsMilliseconds()
+ {
+ $producer = new PheanstalkProducer($this->createPheanstalkMock());
+ $producer->setDeliveryDelay(5000);
+
+ $this->assertEquals(5000, $producer->getDeliveryDelay());
+ }
+
+ public function testDeliveryDelayResolvesToSeconds()
+ {
+ $message = new PheanstalkMessage('theBody');
+
+ $pheanstalk = $this->createPheanstalkMock();
+ $pheanstalk
+ ->expects($this->once())
+ ->method('useTube')
+ ->with('theQueueName')
+ ->willReturnSelf()
+ ;
+ $pheanstalk
+ ->expects($this->once())
+ ->method('put')
+ ->with('{"body":"theBody","properties":[],"headers":[]}', Pheanstalk::DEFAULT_PRIORITY, 5, Pheanstalk::DEFAULT_TTR)
+ ;
+
+ $producer = new PheanstalkProducer($pheanstalk);
+ $producer->setDeliveryDelay(5000);
+
+ $producer->send(
+ new PheanstalkDestination('theQueueName'),
+ $message
+ );
+ }
+
+ public function testMessageDelayPrecedesDeliveryDelay()
+ {
+ $message = new PheanstalkMessage('theBody');
+ $message->setDelay(25);
+
+ $pheanstalk = $this->createPheanstalkMock();
+ $pheanstalk
+ ->expects($this->once())
+ ->method('useTube')
+ ->with('theQueueName')
+ ->willReturnSelf()
+ ;
+ $pheanstalk
+ ->expects($this->once())
+ ->method('put')
+ ->with('{"body":"theBody","properties":[],"headers":{"delay":25}}', Pheanstalk::DEFAULT_PRIORITY, 25, Pheanstalk::DEFAULT_TTR)
+ ;
+
+ $producer = new PheanstalkProducer($pheanstalk);
+ $producer->setDeliveryDelay(1000);
+
+ $producer->send(
+ new PheanstalkDestination('theQueueName'),
+ $message
+ );
+ }
+
+ public function testAccessTimeToLiveAsMilliseconds()
+ {
+ $producer = new PheanstalkProducer($this->createPheanstalkMock());
+ $producer->setTimeToLive(5000);
+
+ $this->assertEquals(5000, $producer->getTimeToLive());
+ }
+
+ public function testTimeToLiveResolvesToSeconds()
+ {
+ $message = new PheanstalkMessage('theBody');
+
+ $pheanstalk = $this->createPheanstalkMock();
+ $pheanstalk
+ ->expects($this->once())
+ ->method('useTube')
+ ->with('theQueueName')
+ ->willReturnSelf()
+ ;
+ $pheanstalk
+ ->expects($this->once())
+ ->method('put')
+ ->with('{"body":"theBody","properties":[],"headers":[]}', Pheanstalk::DEFAULT_PRIORITY, Pheanstalk::DEFAULT_DELAY, 5)
+ ;
+
+ $producer = new PheanstalkProducer($pheanstalk);
+ $producer->setTimeToLive(5000);
+
+ $producer->send(
+ new PheanstalkDestination('theQueueName'),
+ $message
+ );
+ }
+
+ public function testMessageTimeToRunPrecedesTimeToLive()
+ {
+ $message = new PheanstalkMessage('theBody');
+ $message->setTimeToRun(25);
+
+ $pheanstalk = $this->createPheanstalkMock();
+ $pheanstalk
+ ->expects($this->once())
+ ->method('useTube')
+ ->with('theQueueName')
+ ->willReturnSelf()
+ ;
+ $pheanstalk
+ ->expects($this->once())
+ ->method('put')
+ ->with('{"body":"theBody","properties":[],"headers":{"ttr":25}}', Pheanstalk::DEFAULT_PRIORITY, Pheanstalk::DEFAULT_DELAY, 25)
+ ;
+
+ $producer = new PheanstalkProducer($pheanstalk);
+ $producer->setTimeToLive(1000);
+
+ $producer->send(
+ new PheanstalkDestination('theQueueName'),
+ $message
+ );
+ }
+
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Pheanstalk
+ * @return MockObject|Pheanstalk
*/
private function createPheanstalkMock()
{
diff --git a/pkg/pheanstalk/Tests/Spec/PheanstalkConnectionFactoryTest.php b/pkg/pheanstalk/Tests/Spec/PheanstalkConnectionFactoryTest.php
index e05152599..4d9148447 100644
--- a/pkg/pheanstalk/Tests/Spec/PheanstalkConnectionFactoryTest.php
+++ b/pkg/pheanstalk/Tests/Spec/PheanstalkConnectionFactoryTest.php
@@ -7,9 +7,6 @@
class PheanstalkConnectionFactoryTest extends ConnectionFactorySpec
{
- /**
- * {@inheritdoc}
- */
protected function createConnectionFactory()
{
return new PheanstalkConnectionFactory();
diff --git a/pkg/pheanstalk/Tests/Spec/PheanstalkContextTest.php b/pkg/pheanstalk/Tests/Spec/PheanstalkContextTest.php
index d69a41ef6..d6ea514f4 100644
--- a/pkg/pheanstalk/Tests/Spec/PheanstalkContextTest.php
+++ b/pkg/pheanstalk/Tests/Spec/PheanstalkContextTest.php
@@ -8,9 +8,6 @@
class PheanstalkContextTest extends ContextSpec
{
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return new PheanstalkContext($this->createMock(Pheanstalk::class));
diff --git a/pkg/pheanstalk/Tests/Spec/PheanstalkMessageTest.php b/pkg/pheanstalk/Tests/Spec/PheanstalkMessageTest.php
index 30fb1cf1b..692e0db54 100644
--- a/pkg/pheanstalk/Tests/Spec/PheanstalkMessageTest.php
+++ b/pkg/pheanstalk/Tests/Spec/PheanstalkMessageTest.php
@@ -7,9 +7,6 @@
class PheanstalkMessageTest extends MessageSpec
{
- /**
- * {@inheritdoc}
- */
protected function createMessage()
{
return new PheanstalkMessage();
diff --git a/pkg/pheanstalk/Tests/Spec/PheanstalkQueueTest.php b/pkg/pheanstalk/Tests/Spec/PheanstalkQueueTest.php
index a71dc4687..0a770b2e2 100644
--- a/pkg/pheanstalk/Tests/Spec/PheanstalkQueueTest.php
+++ b/pkg/pheanstalk/Tests/Spec/PheanstalkQueueTest.php
@@ -7,9 +7,6 @@
class PheanstalkQueueTest extends QueueSpec
{
- /**
- * {@inheritdoc}
- */
protected function createQueue()
{
return new PheanstalkDestination(self::EXPECTED_QUEUE_NAME);
diff --git a/pkg/pheanstalk/Tests/Spec/PheanstalkSendToAndReceiveFromQueueTest.php b/pkg/pheanstalk/Tests/Spec/PheanstalkSendToAndReceiveFromQueueTest.php
index 45d0040b4..282ac364c 100644
--- a/pkg/pheanstalk/Tests/Spec/PheanstalkSendToAndReceiveFromQueueTest.php
+++ b/pkg/pheanstalk/Tests/Spec/PheanstalkSendToAndReceiveFromQueueTest.php
@@ -12,9 +12,6 @@
*/
class PheanstalkSendToAndReceiveFromQueueTest extends SendToAndReceiveFromQueueSpec
{
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
$factory = new PheanstalkConnectionFactory(getenv('BEANSTALKD_DSN'));
@@ -23,8 +20,7 @@ protected function createContext()
}
/**
- * @param Context $context
- * @param string $queueName
+ * @param string $queueName
*
* @return Queue
*/
diff --git a/pkg/pheanstalk/Tests/Spec/PheanstalkSendToAndReceiveNoWaitFromQueueTest.php b/pkg/pheanstalk/Tests/Spec/PheanstalkSendToAndReceiveNoWaitFromQueueTest.php
index 8226b512e..de464e5bf 100644
--- a/pkg/pheanstalk/Tests/Spec/PheanstalkSendToAndReceiveNoWaitFromQueueTest.php
+++ b/pkg/pheanstalk/Tests/Spec/PheanstalkSendToAndReceiveNoWaitFromQueueTest.php
@@ -11,9 +11,6 @@
*/
class PheanstalkSendToAndReceiveNoWaitFromQueueTest extends SendToAndReceiveNoWaitFromQueueSpec
{
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
$factory = new PheanstalkConnectionFactory(getenv('BEANSTALKD_DSN'));
@@ -21,9 +18,6 @@ protected function createContext()
return $factory->createContext();
}
- /**
- * {@inheritdoc}
- */
protected function createQueue(Context $context, $queueName)
{
return $context->createQueue($queueName.time());
diff --git a/pkg/pheanstalk/Tests/Spec/PheanstalkSendToTopicAndReceiveFromQueueTest.php b/pkg/pheanstalk/Tests/Spec/PheanstalkSendToTopicAndReceiveFromQueueTest.php
index a6a5f925a..4c30d7796 100644
--- a/pkg/pheanstalk/Tests/Spec/PheanstalkSendToTopicAndReceiveFromQueueTest.php
+++ b/pkg/pheanstalk/Tests/Spec/PheanstalkSendToTopicAndReceiveFromQueueTest.php
@@ -13,14 +13,11 @@ class PheanstalkSendToTopicAndReceiveFromQueueTest extends SendToTopicAndReceive
{
private $time;
- public function setUp()
+ protected function setUp(): void
{
$this->time = time();
}
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
$factory = new PheanstalkConnectionFactory(getenv('BEANSTALKD_DSN'));
@@ -28,17 +25,11 @@ protected function createContext()
return $factory->createContext();
}
- /**
- * {@inheritdoc}
- */
protected function createQueue(Context $context, $queueName)
{
return $context->createQueue($queueName.$this->time);
}
- /**
- * {@inheritdoc}
- */
protected function createTopic(Context $context, $topicName)
{
return $context->createTopic($topicName.$this->time);
diff --git a/pkg/pheanstalk/Tests/Spec/PheanstalkSendToTopicAndReceiveNoWaitFromQueueTest.php b/pkg/pheanstalk/Tests/Spec/PheanstalkSendToTopicAndReceiveNoWaitFromQueueTest.php
index 2bf9f9542..58e8b71f4 100644
--- a/pkg/pheanstalk/Tests/Spec/PheanstalkSendToTopicAndReceiveNoWaitFromQueueTest.php
+++ b/pkg/pheanstalk/Tests/Spec/PheanstalkSendToTopicAndReceiveNoWaitFromQueueTest.php
@@ -13,14 +13,11 @@ class PheanstalkSendToTopicAndReceiveNoWaitFromQueueTest extends SendToTopicAndR
{
private $time;
- public function setUp()
+ protected function setUp(): void
{
$this->time = time();
}
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
$factory = new PheanstalkConnectionFactory(getenv('BEANSTALKD_DSN'));
@@ -28,17 +25,11 @@ protected function createContext()
return $factory->createContext();
}
- /**
- * {@inheritdoc}
- */
protected function createQueue(Context $context, $queueName)
{
return $context->createQueue($queueName.$this->time);
}
- /**
- * {@inheritdoc}
- */
protected function createTopic(Context $context, $topicName)
{
return $context->createTopic($topicName.$this->time);
diff --git a/pkg/pheanstalk/Tests/Spec/PheanstalkTopicTest.php b/pkg/pheanstalk/Tests/Spec/PheanstalkTopicTest.php
index d15d51083..4b0028261 100644
--- a/pkg/pheanstalk/Tests/Spec/PheanstalkTopicTest.php
+++ b/pkg/pheanstalk/Tests/Spec/PheanstalkTopicTest.php
@@ -7,9 +7,6 @@
class PheanstalkTopicTest extends TopicSpec
{
- /**
- * {@inheritdoc}
- */
protected function createTopic()
{
return new PheanstalkDestination(self::EXPECTED_TOPIC_NAME);
diff --git a/pkg/pheanstalk/composer.json b/pkg/pheanstalk/composer.json
index dcf5408c8..c810971c8 100644
--- a/pkg/pheanstalk/composer.json
+++ b/pkg/pheanstalk/composer.json
@@ -6,15 +6,15 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "pda/pheanstalk": "^3",
- "queue-interop/queue-interop": "0.7.x-dev"
+ "php": "^8.1",
+ "pda/pheanstalk": "^3.1",
+ "queue-interop/queue-interop": "^0.8"
},
"require-dev": {
- "phpunit/phpunit": "~5.4.0",
- "enqueue/test": "0.9.x-dev",
- "enqueue/null": "0.9.x-dev",
- "queue-interop/queue-spec": "0.6.x-dev"
+ "phpunit/phpunit": "^9.5",
+ "enqueue/test": "0.10.x-dev",
+ "enqueue/null": "0.10.x-dev",
+ "queue-interop/queue-spec": "^0.6.2"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -32,7 +32,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/pheanstalk/phpunit.xml.dist b/pkg/pheanstalk/phpunit.xml.dist
index 4dca142e1..1e72c01a2 100644
--- a/pkg/pheanstalk/phpunit.xml.dist
+++ b/pkg/pheanstalk/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/rdkafka/.gitattributes b/pkg/rdkafka/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/rdkafka/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/rdkafka/.github/workflows/ci.yml b/pkg/rdkafka/.github/workflows/ci.yml
new file mode 100644
index 000000000..928d46fa9
--- /dev/null
+++ b/pkg/rdkafka/.github/workflows/ci.yml
@@ -0,0 +1,31 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+ with: # ext-rdkafka not needed for tests, and a pain to install on CI;
+ composer-options: "--ignore-platform-req=ext-rdkafka"
+
+ - run: sed -i 's/525568/16777471/' vendor/kwn/php-rdkafka-stubs/stubs/constants.php
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/rdkafka/.travis.yml b/pkg/rdkafka/.travis.yml
deleted file mode 100644
index 5556e8f9c..000000000
--- a/pkg/rdkafka/.travis.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-sudo: false
-
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
- - '7.2'
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - php Tests/fix_composer_json.php
- - composer self-update
- - composer install
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/rdkafka/JsonSerializer.php b/pkg/rdkafka/JsonSerializer.php
index ae161ca08..1d25ea55e 100644
--- a/pkg/rdkafka/JsonSerializer.php
+++ b/pkg/rdkafka/JsonSerializer.php
@@ -14,12 +14,8 @@ public function toString(RdKafkaMessage $message): string
'headers' => $message->getHeaders(),
]);
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'The malformed json given. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
}
return $json;
@@ -28,12 +24,8 @@ public function toString(RdKafkaMessage $message): string
public function toMessage(string $string): RdKafkaMessage
{
$data = json_decode($string, true);
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'The malformed json given. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
}
return new RdKafkaMessage($data['body'], $data['properties'], $data['headers']);
diff --git a/pkg/rdkafka/README.md b/pkg/rdkafka/README.md
index d0e0bede5..7e0502edd 100644
--- a/pkg/rdkafka/README.md
+++ b/pkg/rdkafka/README.md
@@ -1,26 +1,39 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# RdKafka Transport
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/rdkafka)
+[](https://github.com/php-enqueue/rdkafka/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/rdkafka)
[](https://packagist.org/packages/enqueue/rdkafka)
-
-This is an implementation of Queue Interop specification. It allows you to send and consume message via Kafka protocol.
+
+This is an implementation of Queue Interop specification. It allows you to send and consume message via Kafka protocol.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/transport/kafka/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
diff --git a/pkg/rdkafka/RdKafkaConnectionFactory.php b/pkg/rdkafka/RdKafkaConnectionFactory.php
index 8a634a1be..24d60c9b6 100644
--- a/pkg/rdkafka/RdKafkaConnectionFactory.php
+++ b/pkg/rdkafka/RdKafkaConnectionFactory.php
@@ -28,6 +28,7 @@ class RdKafkaConnectionFactory implements ConnectionFactory
* 'partitioner' => null, // https://arnaud-lb.github.io/php-rdkafka/phpdoc/rdkafka-topicconf.setpartitioner.html
* 'log_level' => null,
* 'commit_async' => false,
+ * 'shutdown_timeout' => -1, // https://github.com/arnaud-lb/php-rdkafka#proper-shutdown
* ]
*
* or
@@ -38,6 +39,10 @@ class RdKafkaConnectionFactory implements ConnectionFactory
*/
public function __construct($config = 'kafka:')
{
+ if (version_compare(RdKafkaContext::getLibrdKafkaVersion(), '1.0.0', '<')) {
+ throw new \RuntimeException('You must install librdkafka:1.0.0 or higher');
+ }
+
if (empty($config) || 'kafka:' === $config) {
$config = [];
} elseif (is_string($config)) {
diff --git a/pkg/rdkafka/RdKafkaConsumer.php b/pkg/rdkafka/RdKafkaConsumer.php
index 5e89f3d34..8b6cf12c6 100644
--- a/pkg/rdkafka/RdKafkaConsumer.php
+++ b/pkg/rdkafka/RdKafkaConsumer.php
@@ -51,7 +51,7 @@ public function __construct(KafkaConsumer $consumer, RdKafkaContext $context, Rd
$this->context = $context;
$this->topic = $topic;
$this->subscribed = false;
- $this->commitAsync = false;
+ $this->commitAsync = true;
$this->setSerializer($serializer);
}
@@ -66,7 +66,12 @@ public function setCommitAsync(bool $async): void
$this->commitAsync = $async;
}
- public function setOffset(int $offset = null): void
+ public function getOffset(): ?int
+ {
+ return $this->offset;
+ }
+
+ public function setOffset(?int $offset = null): void
{
if ($this->subscribed) {
throw new \LogicException('The consumer has already subscribed.');
@@ -75,6 +80,9 @@ public function setOffset(int $offset = null): void
$this->offset = $offset;
}
+ /**
+ * @return RdKafkaTopic
+ */
public function getQueue(): Queue
{
return $this->topic;
@@ -99,18 +107,17 @@ public function receive(int $timeout = 0): ?Message
$this->subscribed = true;
}
- $message = null;
if ($timeout > 0) {
- $message = $this->doReceive($timeout);
- } else {
- while (true) {
- if ($message = $this->doReceive(500)) {
- break;
- }
+ return $this->doReceive($timeout);
+ }
+
+ while (true) {
+ if ($message = $this->doReceive(500)) {
+ return $message;
}
}
- return $message;
+ return null;
}
/**
@@ -155,22 +162,31 @@ private function doReceive(int $timeout): ?RdKafkaMessage
{
$kafkaMessage = $this->consumer->consume($timeout);
+ if (null === $kafkaMessage) {
+ return null;
+ }
+
switch ($kafkaMessage->err) {
- case RD_KAFKA_RESP_ERR__PARTITION_EOF:
- case RD_KAFKA_RESP_ERR__TIMED_OUT:
- break;
- case RD_KAFKA_RESP_ERR_NO_ERROR:
+ case \RD_KAFKA_RESP_ERR__PARTITION_EOF:
+ case \RD_KAFKA_RESP_ERR__TIMED_OUT:
+ case \RD_KAFKA_RESP_ERR__TRANSPORT:
+ return null;
+ case \RD_KAFKA_RESP_ERR_NO_ERROR:
$message = $this->serializer->toMessage($kafkaMessage->payload);
$message->setKey($kafkaMessage->key);
$message->setPartition($kafkaMessage->partition);
$message->setKafkaMessage($kafkaMessage);
+ // Merge headers passed from Kafka with possible earlier serialized payload headers. Prefer Kafka's.
+ // Note: Requires phprdkafka >= 3.1.0
+ if (isset($kafkaMessage->headers)) {
+ $message->setHeaders(array_merge($message->getHeaders(), $kafkaMessage->headers));
+ }
+
return $message;
default:
throw new \LogicException($kafkaMessage->errstr(), $kafkaMessage->err);
break;
}
-
- return null;
}
}
diff --git a/pkg/rdkafka/RdKafkaContext.php b/pkg/rdkafka/RdKafkaContext.php
index cfe8e0eb1..a252fcfd5 100644
--- a/pkg/rdkafka/RdKafkaContext.php
+++ b/pkg/rdkafka/RdKafkaContext.php
@@ -19,7 +19,6 @@
use RdKafka\Conf;
use RdKafka\KafkaConsumer;
use RdKafka\Producer as VendorProducer;
-use RdKafka\TopicConf;
class RdKafkaContext implements Context
{
@@ -36,7 +35,7 @@ class RdKafkaContext implements Context
private $conf;
/**
- * @var Producer
+ * @var RdKafkaProducer
*/
private $producer;
@@ -46,12 +45,15 @@ class RdKafkaContext implements Context
private $kafkaConsumers;
/**
- * @param array $config
+ * @var RdKafkaConsumer[]
*/
+ private $rdKafkaConsumers;
+
public function __construct(array $config)
{
$this->config = $config;
$this->kafkaConsumers = [];
+ $this->rdKafkaConsumers = [];
$this->setSerializer(new JsonSerializer());
}
@@ -90,7 +92,23 @@ public function createTemporaryQueue(): Queue
*/
public function createProducer(): Producer
{
- return new RdKafkaProducer($this->getProducer(), $this->getSerializer());
+ if (!isset($this->producer)) {
+ $producer = new VendorProducer($this->getConf());
+
+ if (isset($this->config['log_level'])) {
+ $producer->setLogLevel($this->config['log_level']);
+ }
+
+ $this->producer = new RdKafkaProducer($producer, $this->getSerializer());
+
+ // Once created RdKafkaProducer can store messages internally that need to be delivered before PHP shuts
+ // down. Otherwise, we are bound to lose messages in transit.
+ // Note that it is generally preferable to call "close" method explicitly before shutdown starts, since
+ // otherwise we might not have access to some objects, like database connections.
+ register_shutdown_function([$this->producer, 'flush'], $this->config['shutdown_timeout'] ?? -1);
+ }
+
+ return $this->producer;
}
/**
@@ -102,30 +120,42 @@ public function createConsumer(Destination $destination): Consumer
{
InvalidDestinationException::assertDestinationInstanceOf($destination, RdKafkaTopic::class);
- $this->kafkaConsumers[] = $kafkaConsumer = new KafkaConsumer($this->getConf());
+ $queueName = $destination->getQueueName();
- $consumer = new RdKafkaConsumer(
- $kafkaConsumer,
- $this,
- $destination,
- $this->getSerializer()
- );
+ if (!isset($this->rdKafkaConsumers[$queueName])) {
+ $this->kafkaConsumers[] = $kafkaConsumer = new KafkaConsumer($this->getConf());
+
+ $consumer = new RdKafkaConsumer(
+ $kafkaConsumer,
+ $this,
+ $destination,
+ $this->getSerializer()
+ );
+
+ if (isset($this->config['commit_async'])) {
+ $consumer->setCommitAsync($this->config['commit_async']);
+ }
- if (isset($this->config['commit_async'])) {
- $consumer->setCommitAsync($this->config['commit_async']);
+ $this->rdKafkaConsumers[$queueName] = $consumer;
}
- return $consumer;
+ return $this->rdKafkaConsumers[$queueName];
}
public function close(): void
{
$kafkaConsumers = $this->kafkaConsumers;
$this->kafkaConsumers = [];
+ $this->rdKafkaConsumers = [];
foreach ($kafkaConsumers as $kafkaConsumer) {
$kafkaConsumer->unsubscribe();
}
+
+ // Compatibility with phprdkafka 4.0.
+ if (isset($this->producer)) {
+ $this->producer->flush($this->config['shutdown_timeout'] ?? -1);
+ }
}
public function createSubscriptionConsumer(): SubscriptionConsumer
@@ -138,36 +168,33 @@ public function purgeQueue(Queue $queue): void
throw PurgeQueueNotSupportedException::providerDoestNotSupportIt();
}
- private function getProducer(): VendorProducer
+ public static function getLibrdKafkaVersion(): string
{
- if (null === $this->producer) {
- $this->producer = new VendorProducer($this->getConf());
-
- if (isset($this->config['log_level'])) {
- $this->producer->setLogLevel($this->config['log_level']);
- }
+ if (!defined('RD_KAFKA_VERSION')) {
+ throw new \RuntimeException('RD_KAFKA_VERSION constant is not defined. Phprdkafka is probably not installed');
}
+ $major = (\RD_KAFKA_VERSION & 0xFF000000) >> 24;
+ $minor = (\RD_KAFKA_VERSION & 0x00FF0000) >> 16;
+ $patch = (\RD_KAFKA_VERSION & 0x0000FF00) >> 8;
- return $this->producer;
+ return "$major.$minor.$patch";
}
private function getConf(): Conf
{
if (null === $this->conf) {
- $topicConf = new TopicConf();
+ $this->conf = new Conf();
if (isset($this->config['topic']) && is_array($this->config['topic'])) {
foreach ($this->config['topic'] as $key => $value) {
- $topicConf->set($key, $value);
+ $this->conf->set($key, $value);
}
}
if (isset($this->config['partitioner'])) {
- $topicConf->setPartitioner($this->config['partitioner']);
+ $this->conf->set('partitioner', $this->config['partitioner']);
}
- $this->conf = new Conf();
-
if (isset($this->config['global']) && is_array($this->config['global'])) {
foreach ($this->config['global'] as $key => $value) {
$this->conf->set($key, $value);
@@ -186,7 +213,9 @@ private function getConf(): Conf
$this->conf->setRebalanceCb($this->config['rebalance_cb']);
}
- $this->conf->setDefaultTopicConf($topicConf);
+ if (isset($this->config['stats_cb'])) {
+ $this->conf->setStatsCb($this->config['stats_cb']);
+ }
}
return $this->conf;
diff --git a/pkg/rdkafka/RdKafkaMessage.php b/pkg/rdkafka/RdKafkaMessage.php
index 0785a5644..7c6d0d005 100644
--- a/pkg/rdkafka/RdKafkaMessage.php
+++ b/pkg/rdkafka/RdKafkaMessage.php
@@ -112,7 +112,7 @@ public function setRedelivered(bool $redelivered): void
$this->redelivered = $redelivered;
}
- public function setCorrelationId(string $correlationId = null): void
+ public function setCorrelationId(?string $correlationId = null): void
{
$this->setHeader('correlation_id', (string) $correlationId);
}
@@ -122,7 +122,7 @@ public function getCorrelationId(): ?string
return $this->getHeader('correlation_id');
}
- public function setMessageId(string $messageId = null): void
+ public function setMessageId(?string $messageId = null): void
{
$this->setHeader('message_id', (string) $messageId);
}
@@ -139,12 +139,12 @@ public function getTimestamp(): ?int
return null === $value ? null : (int) $value;
}
- public function setTimestamp(int $timestamp = null): void
+ public function setTimestamp(?int $timestamp = null): void
{
$this->setHeader('timestamp', $timestamp);
}
- public function setReplyTo(string $replyTo = null): void
+ public function setReplyTo(?string $replyTo = null): void
{
$this->setHeader('reply_to', $replyTo);
}
@@ -159,7 +159,7 @@ public function getPartition(): ?int
return $this->partition;
}
- public function setPartition(int $partition = null): void
+ public function setPartition(?int $partition = null): void
{
$this->partition = $partition;
}
@@ -169,7 +169,7 @@ public function getKey(): ?string
return $this->key;
}
- public function setKey(string $key = null): void
+ public function setKey(?string $key = null): void
{
$this->key = $key;
}
@@ -179,7 +179,7 @@ public function getKafkaMessage(): ?VendorMessage
return $this->kafkaMessage;
}
- public function setKafkaMessage(VendorMessage $message = null): void
+ public function setKafkaMessage(?VendorMessage $message = null): void
{
$this->kafkaMessage = $message;
}
diff --git a/pkg/rdkafka/RdKafkaProducer.php b/pkg/rdkafka/RdKafkaProducer.php
index feb40c46b..24589b3e7 100644
--- a/pkg/rdkafka/RdKafkaProducer.php
+++ b/pkg/rdkafka/RdKafkaProducer.php
@@ -7,6 +7,7 @@
use Interop\Queue\Destination;
use Interop\Queue\Exception\InvalidDestinationException;
use Interop\Queue\Exception\InvalidMessageException;
+use Interop\Queue\Exception\PriorityNotSupportedException;
use Interop\Queue\Message;
use Interop\Queue\Producer;
use RdKafka\Producer as VendorProducer;
@@ -36,18 +37,40 @@ public function send(Destination $destination, Message $message): void
InvalidDestinationException::assertDestinationInstanceOf($destination, RdKafkaTopic::class);
InvalidMessageException::assertMessageInstanceOf($message, RdKafkaMessage::class);
- $partition = $message->getPartition() ?: $destination->getPartition() ?: RD_KAFKA_PARTITION_UA;
+ $partition = $message->getPartition() ?? $destination->getPartition() ?? \RD_KAFKA_PARTITION_UA;
$payload = $this->serializer->toString($message);
- $key = $message->getKey() ?: $destination->getKey() ?: null;
+ $key = $message->getKey() ?? $destination->getKey() ?? null;
$topic = $this->producer->newTopic($destination->getTopicName(), $destination->getConf());
- $topic->produce($partition, 0 /* must be 0 */, $payload, $key);
+
+ // Note: Topic::producev method exists in phprdkafka > 3.1.0
+ // Headers in payload are maintained for backwards compatibility with apps that might run on lower phprdkafka version
+ if (method_exists($topic, 'producev')) {
+ // Phprdkafka <= 3.1.0 will fail calling `producev` on librdkafka >= 1.0.0 causing segfault
+ // Since we are forcing to use at least librdkafka:1.0.0, no need to check the lib version anymore
+ if (false !== phpversion('rdkafka')
+ && version_compare(phpversion('rdkafka'), '3.1.0', '<=')) {
+ trigger_error(
+ 'Phprdkafka <= 3.1.0 is incompatible with librdkafka 1.0.0 when calling `producev`. '.
+ 'Falling back to `produce` (without message headers) instead.',
+ \E_USER_WARNING
+ );
+ } else {
+ $topic->producev($partition, 0 /* must be 0 */ , $payload, $key, $message->getHeaders());
+ $this->producer->poll(0);
+
+ return;
+ }
+ }
+
+ $topic->produce($partition, 0 /* must be 0 */ , $payload, $key);
+ $this->producer->poll(0);
}
/**
* @return RdKafkaProducer
*/
- public function setDeliveryDelay(int $deliveryDelay = null): Producer
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
{
if (null === $deliveryDelay) {
return $this;
@@ -64,13 +87,13 @@ public function getDeliveryDelay(): ?int
/**
* @return RdKafkaProducer
*/
- public function setPriority(int $priority = null): Producer
+ public function setPriority(?int $priority = null): Producer
{
if (null === $priority) {
return $this;
}
- throw new \LogicException('Not implemented');
+ throw PriorityNotSupportedException::providerDoestNotSupportIt();
}
public function getPriority(): ?int
@@ -78,7 +101,7 @@ public function getPriority(): ?int
return null;
}
- public function setTimeToLive(int $timeToLive = null): Producer
+ public function setTimeToLive(?int $timeToLive = null): Producer
{
if (null === $timeToLive) {
return $this;
@@ -91,4 +114,14 @@ public function getTimeToLive(): ?int
{
return null;
}
+
+ public function flush(int $timeout): ?int
+ {
+ // Flush method is exposed in phprdkafka 4.0
+ if (method_exists($this->producer, 'flush')) {
+ return $this->producer->flush($timeout);
+ }
+
+ return null;
+ }
}
diff --git a/pkg/rdkafka/RdKafkaTopic.php b/pkg/rdkafka/RdKafkaTopic.php
index a7bde1021..572f4d024 100644
--- a/pkg/rdkafka/RdKafkaTopic.php
+++ b/pkg/rdkafka/RdKafkaTopic.php
@@ -50,7 +50,7 @@ public function getConf(): ?TopicConf
return $this->conf;
}
- public function setConf(TopicConf $conf = null): void
+ public function setConf(?TopicConf $conf = null): void
{
$this->conf = $conf;
}
@@ -60,7 +60,7 @@ public function getPartition(): ?int
return $this->partition;
}
- public function setPartition(int $partition = null): void
+ public function setPartition(?int $partition = null): void
{
$this->partition = $partition;
}
@@ -70,7 +70,7 @@ public function getKey(): ?string
return $this->key;
}
- public function setKey(string $key = null): void
+ public function setKey(?string $key = null): void
{
$this->key = $key;
}
diff --git a/pkg/rdkafka/SerializerAwareTrait.php b/pkg/rdkafka/SerializerAwareTrait.php
index d640f93cb..1cd1fac20 100644
--- a/pkg/rdkafka/SerializerAwareTrait.php
+++ b/pkg/rdkafka/SerializerAwareTrait.php
@@ -11,9 +11,6 @@ trait SerializerAwareTrait
*/
private $serializer;
- /**
- * @param Serializer $serializer
- */
public function setSerializer(Serializer $serializer)
{
$this->serializer = $serializer;
diff --git a/pkg/rdkafka/Tests/JsonSerializerTest.php b/pkg/rdkafka/Tests/JsonSerializerTest.php
index 6513a2257..6c9bbef84 100644
--- a/pkg/rdkafka/Tests/JsonSerializerTest.php
+++ b/pkg/rdkafka/Tests/JsonSerializerTest.php
@@ -8,9 +8,6 @@
use Enqueue\Test\ClassExtensionTrait;
use PHPUnit\Framework\TestCase;
-/**
- * @group rdkafka
- */
class JsonSerializerTest extends TestCase
{
use ClassExtensionTrait;
@@ -20,11 +17,6 @@ public function testShouldImplementSerializerInterface()
$this->assertClassImplements(Serializer::class, JsonSerializer::class);
}
- public function testCouldBeConstructedWithoutAnyArguments()
- {
- new JsonSerializer();
- }
-
public function testShouldConvertMessageToJsonString()
{
$serializer = new JsonSerializer();
@@ -42,8 +34,8 @@ public function testThrowIfFailedToEncodeMessageToJson()
$resource = fopen(__FILE__, 'r');
- //guard
- $this->assertInternalType('resource', $resource);
+ // guard
+ $this->assertIsResource($resource);
$message = new RdKafkaMessage('theBody', ['aProp' => $resource]);
diff --git a/pkg/rdkafka/Tests/RdKafkaConnectionFactoryConfigTest.php b/pkg/rdkafka/Tests/RdKafkaConnectionFactoryConfigTest.php
index d3a6a5dab..7ecb1bd7f 100644
--- a/pkg/rdkafka/Tests/RdKafkaConnectionFactoryConfigTest.php
+++ b/pkg/rdkafka/Tests/RdKafkaConnectionFactoryConfigTest.php
@@ -4,6 +4,7 @@
use Enqueue\RdKafka\RdKafkaConnectionFactory;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use PHPUnit\Framework\TestCase;
/**
@@ -12,6 +13,7 @@
class RdKafkaConnectionFactoryConfigTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testThrowNeitherArrayStringNorNullGivenAsConfig()
{
@@ -31,15 +33,12 @@ public function testThrowIfSchemeIsNotSupported()
/**
* @dataProvider provideConfigs
- *
- * @param mixed $config
- * @param mixed $expectedConfig
*/
public function testShouldParseConfigurationAsExpected($config, $expectedConfig)
{
$factory = new RdKafkaConnectionFactory($config);
- $config = $this->getObjectAttribute($factory, 'config');
+ $config = $this->readAttribute($factory, 'config');
$this->assertNotEmpty($config['global']['group.id']);
diff --git a/pkg/rdkafka/Tests/RdKafkaConnectionFactoryTest.php b/pkg/rdkafka/Tests/RdKafkaConnectionFactoryTest.php
index 47fdc1715..d7121da65 100644
--- a/pkg/rdkafka/Tests/RdKafkaConnectionFactoryTest.php
+++ b/pkg/rdkafka/Tests/RdKafkaConnectionFactoryTest.php
@@ -3,13 +3,13 @@
namespace Enqueue\RdKafka\Tests;
use Enqueue\RdKafka\RdKafkaConnectionFactory;
+use Enqueue\Test\ReadAttributeTrait;
use PHPUnit\Framework\TestCase;
-/**
- * @group rdkafka
- */
class RdKafkaConnectionFactoryTest extends TestCase
{
+ use ReadAttributeTrait;
+
public function testThrowNeitherArrayStringNorNullGivenAsConfig()
{
$this->expectException(\LogicException::class);
@@ -38,7 +38,7 @@ public function testShouldBeExpectedDefaultConfig()
{
$factory = new RdKafkaConnectionFactory(null);
- $config = $this->getObjectAttribute($factory, 'config');
+ $config = $this->readAttribute($factory, 'config');
$this->assertNotEmpty($config['global']['group.id']);
@@ -55,7 +55,7 @@ public function testShouldBeExpectedDefaultDsnConfig()
{
$factory = new RdKafkaConnectionFactory('kafka:');
- $config = $this->getObjectAttribute($factory, 'config');
+ $config = $this->readAttribute($factory, 'config');
$this->assertNotEmpty($config['global']['group.id']);
@@ -70,9 +70,6 @@ public function testShouldBeExpectedDefaultDsnConfig()
/**
* @dataProvider provideConfigs
- *
- * @param mixed $config
- * @param mixed $expectedConfig
*/
public function testShouldParseConfigurationAsExpected($config, $expectedConfig)
{
diff --git a/pkg/rdkafka/Tests/RdKafkaConsumerTest.php b/pkg/rdkafka/Tests/RdKafkaConsumerTest.php
index e35d97fc0..e577dfcca 100644
--- a/pkg/rdkafka/Tests/RdKafkaConsumerTest.php
+++ b/pkg/rdkafka/Tests/RdKafkaConsumerTest.php
@@ -11,21 +11,8 @@
use RdKafka\KafkaConsumer;
use RdKafka\Message;
-/**
- * @group rdkafka
- */
class RdKafkaConsumerTest extends TestCase
{
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new RdKafkaConsumer(
- $this->createKafkaConsumerMock(),
- $this->createContextMock(),
- new RdKafkaTopic(''),
- $this->createSerializerMock()
- );
- }
-
public function testShouldReturnQueueSetInConstructor()
{
$destination = new RdKafkaTopic('');
@@ -45,7 +32,7 @@ public function testShouldReceiveFromQueueAndReturnNullIfNoMessageInQueue()
$destination = new RdKafkaTopic('dest');
$kafkaMessage = new Message();
- $kafkaMessage->err = RD_KAFKA_RESP_ERR__TIMED_OUT;
+ $kafkaMessage->err = \RD_KAFKA_RESP_ERR__TIMED_OUT;
$kafkaConsumer = $this->createKafkaConsumerMock();
$kafkaConsumer
@@ -74,7 +61,7 @@ public function testShouldPassProperlyConfiguredTopicPartitionOnAssign()
$destination = new RdKafkaTopic('dest');
$kafkaMessage = new Message();
- $kafkaMessage->err = RD_KAFKA_RESP_ERR__TIMED_OUT;
+ $kafkaMessage->err = \RD_KAFKA_RESP_ERR__TIMED_OUT;
$kafkaConsumer = $this->createKafkaConsumerMock();
$kafkaConsumer
@@ -104,7 +91,7 @@ public function testShouldSubscribeOnFirstReceiveOnly()
$destination = new RdKafkaTopic('dest');
$kafkaMessage = new Message();
- $kafkaMessage->err = RD_KAFKA_RESP_ERR__TIMED_OUT;
+ $kafkaMessage->err = \RD_KAFKA_RESP_ERR__TIMED_OUT;
$kafkaConsumer = $this->createKafkaConsumerMock();
$kafkaConsumer
@@ -135,7 +122,7 @@ public function testShouldAssignWhenOffsetIsSet()
$destination->setPartition(1);
$kafkaMessage = new Message();
- $kafkaMessage->err = RD_KAFKA_RESP_ERR__TIMED_OUT;
+ $kafkaMessage->err = \RD_KAFKA_RESP_ERR__TIMED_OUT;
$kafkaConsumer = $this->createKafkaConsumerMock();
$kafkaConsumer
@@ -167,7 +154,7 @@ public function testThrowOnOffsetChangeAfterSubscribing()
$destination = new RdKafkaTopic('dest');
$kafkaMessage = new Message();
- $kafkaMessage->err = RD_KAFKA_RESP_ERR__TIMED_OUT;
+ $kafkaMessage->err = \RD_KAFKA_RESP_ERR__TIMED_OUT;
$kafkaConsumer = $this->createKafkaConsumerMock();
$kafkaConsumer
@@ -198,11 +185,12 @@ public function testShouldReceiveFromQueueAndReturnMessageIfMessageInQueue()
{
$destination = new RdKafkaTopic('dest');
- $expectedMessage = new RdKafkaMessage('theBody', ['foo' => 'fooVal'], ['bar' => 'barVal']);
+ $expectedMessage = new RdKafkaMessage('theBody', ['foo' => 'fooVal'], ['bar' => 'barVal']);
$kafkaMessage = new Message();
- $kafkaMessage->err = RD_KAFKA_RESP_ERR_NO_ERROR;
+ $kafkaMessage->err = \RD_KAFKA_RESP_ERR_NO_ERROR;
$kafkaMessage->payload = 'theSerializedMessage';
+ $kafkaMessage->partition = 0;
$kafkaConsumer = $this->createKafkaConsumerMock();
$kafkaConsumer
@@ -263,7 +251,7 @@ public function testShouldAllowGetPreviouslySetSerializer()
$expectedSerializer = $this->createSerializerMock();
- //guard
+ // guard
$this->assertNotSame($consumer->getSerializer(), $expectedSerializer);
$consumer->setSerializer($expectedSerializer);
@@ -272,7 +260,7 @@ public function testShouldAllowGetPreviouslySetSerializer()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|KafkaConsumer
+ * @return \PHPUnit\Framework\MockObject\MockObject|KafkaConsumer
*/
private function createKafkaConsumerMock()
{
@@ -280,7 +268,7 @@ private function createKafkaConsumerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|RdKafkaContext
+ * @return \PHPUnit\Framework\MockObject\MockObject|RdKafkaContext
*/
private function createContextMock()
{
@@ -288,7 +276,7 @@ private function createContextMock()
}
/**
- * @return Serializer|\PHPUnit_Framework_MockObject_MockObject|Serializer
+ * @return Serializer|\PHPUnit\Framework\MockObject\MockObject|Serializer
*/
private function createSerializerMock()
{
diff --git a/pkg/rdkafka/Tests/RdKafkaContextTest.php b/pkg/rdkafka/Tests/RdKafkaContextTest.php
index e787efb55..dc1b597de 100644
--- a/pkg/rdkafka/Tests/RdKafkaContextTest.php
+++ b/pkg/rdkafka/Tests/RdKafkaContextTest.php
@@ -10,9 +10,6 @@
use Interop\Queue\Exception\TemporaryQueueNotSupportedException;
use PHPUnit\Framework\TestCase;
-/**
- * @group rdkafka
- */
class RdKafkaContextTest extends TestCase
{
public function testThrowNotImplementedOnCreateTemporaryQueue()
@@ -69,4 +66,31 @@ public function testShouldInjectItsSerializerToConsumer()
$this->assertSame($context->getSerializer(), $producer->getSerializer());
}
+
+ public function testShouldNotCreateConsumerTwice()
+ {
+ $context = new RdKafkaContext(['global' => [
+ 'group.id' => uniqid('', true),
+ ]]);
+ $queue = $context->createQueue('aQueue');
+
+ $consumer = $context->createConsumer($queue);
+ $consumer2 = $context->createConsumer($queue);
+
+ $this->assertSame($consumer, $consumer2);
+ }
+
+ public function testShouldCreateTwoConsumers()
+ {
+ $context = new RdKafkaContext(['global' => [
+ 'group.id' => uniqid('', true),
+ ]]);
+ $queueA = $context->createQueue('aQueue');
+ $queueB = $context->createQueue('bQueue');
+
+ $consumer = $context->createConsumer($queueA);
+ $consumer2 = $context->createConsumer($queueB);
+
+ $this->assertNotSame($consumer, $consumer2);
+ }
}
diff --git a/pkg/rdkafka/Tests/RdKafkaMessageTest.php b/pkg/rdkafka/Tests/RdKafkaMessageTest.php
index c2e5c224a..9bcc34642 100644
--- a/pkg/rdkafka/Tests/RdKafkaMessageTest.php
+++ b/pkg/rdkafka/Tests/RdKafkaMessageTest.php
@@ -6,9 +6,6 @@
use PHPUnit\Framework\TestCase;
use RdKafka\Message;
-/**
- * @group rdkafka
- */
class RdKafkaMessageTest extends TestCase
{
public function testCouldSetGetPartition()
diff --git a/pkg/rdkafka/Tests/RdKafkaProducerTest.php b/pkg/rdkafka/Tests/RdKafkaProducerTest.php
index be5b94a6a..6295fbc1b 100644
--- a/pkg/rdkafka/Tests/RdKafkaProducerTest.php
+++ b/pkg/rdkafka/Tests/RdKafkaProducerTest.php
@@ -15,16 +15,8 @@
use RdKafka\ProducerTopic;
use RdKafka\TopicConf;
-/**
- * @group rdkafka
- */
class RdKafkaProducerTest extends TestCase
{
- public function testCouldBeConstructedWithKafkaProducerAndSerializerAsArguments()
- {
- new RdKafkaProducer($this->createKafkaProducerMock(), $this->createSerializerMock());
- }
-
public function testThrowIfDestinationInvalid()
{
$producer = new RdKafkaProducer($this->createKafkaProducerMock(), $this->createSerializerMock());
@@ -45,18 +37,20 @@ public function testThrowIfMessageInvalid()
public function testShouldUseSerializerToEncodeMessageAndPutToExpectedTube()
{
- $message = new RdKafkaMessage('theBody', ['foo' => 'fooVal'], ['bar' => 'barVal']);
+ $messageHeaders = ['bar' => 'barVal'];
+ $message = new RdKafkaMessage('theBody', ['foo' => 'fooVal'], $messageHeaders);
$message->setKey('key');
$kafkaTopic = $this->createKafkaTopicMock();
$kafkaTopic
->expects($this->once())
- ->method('produce')
+ ->method('producev')
->with(
- RD_KAFKA_PARTITION_UA,
+ \RD_KAFKA_PARTITION_UA,
0,
'theSerializedMessage',
- 'key'
+ 'key',
+ $messageHeaders
)
;
@@ -67,6 +61,11 @@ public function testShouldUseSerializerToEncodeMessageAndPutToExpectedTube()
->with('theQueueName')
->willReturn($kafkaTopic)
;
+ $kafkaProducer
+ ->expects($this->once())
+ ->method('poll')
+ ->with(0)
+ ;
$serializer = $this->createSerializerMock();
$serializer
@@ -87,7 +86,7 @@ public function testShouldPassNullAsTopicConfigIfNotSetOnTopic()
$kafkaTopic = $this->createKafkaTopicMock();
$kafkaTopic
->expects($this->once())
- ->method('produce')
+ ->method('producev')
;
$kafkaProducer = $this->createKafkaProducerMock();
@@ -97,6 +96,11 @@ public function testShouldPassNullAsTopicConfigIfNotSetOnTopic()
->with('theQueueName', null)
->willReturn($kafkaTopic)
;
+ $kafkaProducer
+ ->expects($this->once())
+ ->method('poll')
+ ->with(0)
+ ;
$serializer = $this->createSerializerMock();
$serializer
@@ -123,7 +127,7 @@ public function testShouldPassCustomConfAsTopicConfigIfSetOnTopic()
$kafkaTopic = $this->createKafkaTopicMock();
$kafkaTopic
->expects($this->once())
- ->method('produce')
+ ->method('producev')
;
$kafkaProducer = $this->createKafkaProducerMock();
@@ -133,6 +137,11 @@ public function testShouldPassCustomConfAsTopicConfigIfSetOnTopic()
->with('theQueueName', $this->identicalTo($conf))
->willReturn($kafkaTopic)
;
+ $kafkaProducer
+ ->expects($this->once())
+ ->method('poll')
+ ->with(0)
+ ;
$serializer = $this->createSerializerMock();
$serializer
@@ -155,7 +164,7 @@ public function testShouldAllowGetPreviouslySetSerializer()
$expectedSerializer = $this->createSerializerMock();
- //guard
+ // guard
$this->assertNotSame($producer->getSerializer(), $expectedSerializer);
$producer->setSerializer($expectedSerializer);
@@ -165,15 +174,16 @@ public function testShouldAllowGetPreviouslySetSerializer()
public function testShouldAllowSerializersToSerializeKeys()
{
- $message = new RdKafkaMessage('theBody', ['foo' => 'fooVal'], ['bar' => 'barVal']);
+ $messageHeaders = ['bar' => 'barVal'];
+ $message = new RdKafkaMessage('theBody', ['foo' => 'fooVal'], $messageHeaders);
$message->setKey('key');
$kafkaTopic = $this->createKafkaTopicMock();
$kafkaTopic
->expects($this->once())
- ->method('produce')
+ ->method('producev')
->with(
- RD_KAFKA_PARTITION_UA,
+ \RD_KAFKA_PARTITION_UA,
0,
'theSerializedMessage',
'theSerializedKey'
@@ -186,6 +196,11 @@ public function testShouldAllowSerializersToSerializeKeys()
->method('newTopic')
->willReturn($kafkaTopic)
;
+ $kafkaProducer
+ ->expects($this->once())
+ ->method('poll')
+ ->with(0)
+ ;
$serializer = $this->createSerializerMock();
$serializer
@@ -202,8 +217,166 @@ public function testShouldAllowSerializersToSerializeKeys()
$producer->send(new RdKafkaTopic('theQueueName'), $message);
}
+ public function testShouldGetPartitionFromMessage(): void
+ {
+ $partition = 1;
+
+ $kafkaTopic = $this->createKafkaTopicMock();
+ $kafkaTopic
+ ->expects($this->once())
+ ->method('producev')
+ ->with(
+ $partition,
+ 0,
+ 'theSerializedMessage',
+ 'theSerializedKey'
+ )
+ ;
+
+ $kafkaProducer = $this->createKafkaProducerMock();
+ $kafkaProducer
+ ->expects($this->once())
+ ->method('newTopic')
+ ->willReturn($kafkaTopic)
+ ;
+ $kafkaProducer
+ ->expects($this->once())
+ ->method('poll')
+ ->with(0)
+ ;
+ $messageHeaders = ['bar' => 'barVal'];
+ $message = new RdKafkaMessage('theBody', ['foo' => 'fooVal'], $messageHeaders);
+ $message->setKey('key');
+ $message->setPartition($partition);
+
+ $serializer = $this->createSerializerMock();
+ $serializer
+ ->expects($this->once())
+ ->method('toString')
+ ->willReturnCallback(function () use ($message) {
+ $message->setKey('theSerializedKey');
+
+ return 'theSerializedMessage';
+ })
+ ;
+
+ $destination = new RdKafkaTopic('theQueueName');
+
+ $producer = new RdKafkaProducer($kafkaProducer, $serializer);
+ $producer->send($destination, $message);
+ }
+
+ public function testShouldGetPartitionFromDestination(): void
+ {
+ $partition = 2;
+
+ $kafkaTopic = $this->createKafkaTopicMock();
+ $kafkaTopic
+ ->expects($this->once())
+ ->method('producev')
+ ->with(
+ $partition,
+ 0,
+ 'theSerializedMessage',
+ 'theSerializedKey'
+ )
+ ;
+
+ $kafkaProducer = $this->createKafkaProducerMock();
+ $kafkaProducer
+ ->expects($this->once())
+ ->method('newTopic')
+ ->willReturn($kafkaTopic)
+ ;
+ $kafkaProducer
+ ->expects($this->once())
+ ->method('poll')
+ ->with(0)
+ ;
+ $messageHeaders = ['bar' => 'barVal'];
+ $message = new RdKafkaMessage('theBody', ['foo' => 'fooVal'], $messageHeaders);
+ $message->setKey('key');
+
+ $serializer = $this->createSerializerMock();
+ $serializer
+ ->expects($this->once())
+ ->method('toString')
+ ->willReturnCallback(function () use ($message) {
+ $message->setKey('theSerializedKey');
+
+ return 'theSerializedMessage';
+ })
+ ;
+
+ $destination = new RdKafkaTopic('theQueueName');
+ $destination->setPartition($partition);
+
+ $producer = new RdKafkaProducer($kafkaProducer, $serializer);
+ $producer->send($destination, $message);
+ }
+
+ public function testShouldAllowFalsyKeyFromMessage(): void
+ {
+ $key = 0;
+
+ $kafkaTopic = $this->createKafkaTopicMock();
+ $kafkaTopic
+ ->expects($this->once())
+ ->method('producev')
+ ->with(
+ \RD_KAFKA_PARTITION_UA,
+ 0,
+ '',
+ $key
+ )
+ ;
+
+ $kafkaProducer = $this->createKafkaProducerMock();
+ $kafkaProducer
+ ->expects($this->once())
+ ->method('newTopic')
+ ->willReturn($kafkaTopic)
+ ;
+
+ $message = new RdKafkaMessage();
+ $message->setKey($key);
+
+ $producer = new RdKafkaProducer($kafkaProducer, $this->createSerializerMock());
+ $producer->send(new RdKafkaTopic(''), $message);
+ }
+
+ public function testShouldAllowFalsyKeyFromDestination(): void
+ {
+ $key = 0;
+
+ $kafkaTopic = $this->createKafkaTopicMock();
+ $kafkaTopic
+ ->expects($this->once())
+ ->method('producev')
+ ->with(
+ \RD_KAFKA_PARTITION_UA,
+ 0,
+ '',
+ $key
+ )
+ ;
+
+ $kafkaProducer = $this->createKafkaProducerMock();
+ $kafkaProducer
+ ->expects($this->once())
+ ->method('newTopic')
+ ->willReturn($kafkaTopic)
+ ;
+
+ $destination = new RdKafkaTopic('');
+ $destination->setKey($key);
+
+ $producer = new RdKafkaProducer($kafkaProducer, $this->createSerializerMock());
+ $producer->send($destination, new RdKafkaMessage());
+ }
+
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|ProducerTopic
+ * @return \PHPUnit\Framework\MockObject\MockObject|ProducerTopic
*/
private function createKafkaTopicMock()
{
@@ -211,7 +384,7 @@ private function createKafkaTopicMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Producer
+ * @return \PHPUnit\Framework\MockObject\MockObject|Producer
*/
private function createKafkaProducerMock()
{
@@ -219,7 +392,7 @@ private function createKafkaProducerMock()
}
/**
- * @return Serializer|\PHPUnit_Framework_MockObject_MockObject|Serializer
+ * @return Serializer|\PHPUnit\Framework\MockObject\MockObject|Serializer
*/
private function createSerializerMock()
{
diff --git a/pkg/rdkafka/Tests/RdKafkaTopicTest.php b/pkg/rdkafka/Tests/RdKafkaTopicTest.php
index 5ed22885a..d0bc8cc13 100644
--- a/pkg/rdkafka/Tests/RdKafkaTopicTest.php
+++ b/pkg/rdkafka/Tests/RdKafkaTopicTest.php
@@ -6,9 +6,6 @@
use PHPUnit\Framework\TestCase;
use RdKafka\TopicConf;
-/**
- * @group rdkafka
- */
class RdKafkaTopicTest extends TestCase
{
public function testCouldSetGetPartition()
diff --git a/pkg/rdkafka/Tests/Spec/RdKafkaConnectionFactoryTest.php b/pkg/rdkafka/Tests/Spec/RdKafkaConnectionFactoryTest.php
index 3327c952d..a582aadca 100644
--- a/pkg/rdkafka/Tests/Spec/RdKafkaConnectionFactoryTest.php
+++ b/pkg/rdkafka/Tests/Spec/RdKafkaConnectionFactoryTest.php
@@ -5,9 +5,6 @@
use Enqueue\RdKafka\RdKafkaConnectionFactory;
use Interop\Queue\Spec\ConnectionFactorySpec;
-/**
- * @group rdkafka
- */
class RdKafkaConnectionFactoryTest extends ConnectionFactorySpec
{
protected function createConnectionFactory()
diff --git a/pkg/rdkafka/Tests/Spec/RdKafkaContextTest.php b/pkg/rdkafka/Tests/Spec/RdKafkaContextTest.php
index fe9625677..d049ca74f 100644
--- a/pkg/rdkafka/Tests/Spec/RdKafkaContextTest.php
+++ b/pkg/rdkafka/Tests/Spec/RdKafkaContextTest.php
@@ -5,9 +5,6 @@
use Enqueue\RdKafka\RdKafkaContext;
use Interop\Queue\Spec\ContextSpec;
-/**
- * @group rdkafka
- */
class RdKafkaContextTest extends ContextSpec
{
protected function createContext()
diff --git a/pkg/rdkafka/Tests/Spec/RdKafkaMessageTest.php b/pkg/rdkafka/Tests/Spec/RdKafkaMessageTest.php
index a29780b0f..9e230d1b6 100644
--- a/pkg/rdkafka/Tests/Spec/RdKafkaMessageTest.php
+++ b/pkg/rdkafka/Tests/Spec/RdKafkaMessageTest.php
@@ -5,14 +5,8 @@
use Enqueue\RdKafka\RdKafkaMessage;
use Interop\Queue\Spec\MessageSpec;
-/**
- * @group rdkafka
- */
class RdKafkaMessageTest extends MessageSpec
{
- /**
- * {@inheritdoc}
- */
protected function createMessage()
{
return new RdKafkaMessage();
diff --git a/pkg/rdkafka/Tests/Spec/RdKafkaQueueTest.php b/pkg/rdkafka/Tests/Spec/RdKafkaQueueTest.php
index 93bc7ac14..863f3e3c5 100644
--- a/pkg/rdkafka/Tests/Spec/RdKafkaQueueTest.php
+++ b/pkg/rdkafka/Tests/Spec/RdKafkaQueueTest.php
@@ -5,9 +5,6 @@
use Enqueue\RdKafka\RdKafkaTopic;
use Interop\Queue\Spec\QueueSpec;
-/**
- * @group rdkafka
- */
class RdKafkaQueueTest extends QueueSpec
{
protected function createQueue()
diff --git a/pkg/rdkafka/Tests/Spec/RdKafkaSendToAndReceiveFromTopicTest.php b/pkg/rdkafka/Tests/Spec/RdKafkaSendToAndReceiveFromTopicTest.php
index 6604eb127..9a969d420 100644
--- a/pkg/rdkafka/Tests/Spec/RdKafkaSendToAndReceiveFromTopicTest.php
+++ b/pkg/rdkafka/Tests/Spec/RdKafkaSendToAndReceiveFromTopicTest.php
@@ -7,8 +7,8 @@
use Interop\Queue\Spec\SendToAndReceiveFromTopicSpec;
/**
- * @group rdkafka
* @group functional
+ *
* @retry 5
*/
class RdKafkaSendToAndReceiveFromTopicTest extends SendToAndReceiveFromTopicSpec
@@ -19,13 +19,19 @@ public function test()
$topic = $this->createTopic($context, uniqid('', true));
- $consumer = $context->createConsumer($topic);
-
$expectedBody = __CLASS__.time();
+ $producer = $context->createProducer();
+ $producer->send($topic, $context->createMessage($expectedBody));
+
+ // Calling close causes Producer to flush (wait for messages to be delivered to Kafka)
+ $context->close();
+
+ $consumer = $context->createConsumer($topic);
$context->createProducer()->send($topic, $context->createMessage($expectedBody));
- $message = $consumer->receive(10000); // 10 sec
+ // Initial balancing can take some time, so we want to make sure the timeout is high enough
+ $message = $consumer->receive(15000); // 15 sec
$this->assertInstanceOf(Message::class, $message);
$consumer->acknowledge($message);
@@ -42,14 +48,12 @@ protected function createContext()
'enable.auto.commit' => 'false',
],
'topic' => [
- 'auto.offset.reset' => 'beginning',
+ 'auto.offset.reset' => 'earliest',
],
];
$context = (new RdKafkaConnectionFactory($config))->createContext();
- sleep(3);
-
return $context;
}
}
diff --git a/pkg/rdkafka/Tests/Spec/RdKafkaTopicTest.php b/pkg/rdkafka/Tests/Spec/RdKafkaTopicTest.php
index 26aacc78d..08d427883 100644
--- a/pkg/rdkafka/Tests/Spec/RdKafkaTopicTest.php
+++ b/pkg/rdkafka/Tests/Spec/RdKafkaTopicTest.php
@@ -5,14 +5,8 @@
use Enqueue\RdKafka\RdKafkaTopic;
use Interop\Queue\Spec\TopicSpec;
-/**
- * @group rdkafka
- */
class RdKafkaTopicTest extends TopicSpec
{
- /**
- * {@inheritdoc}
- */
protected function createTopic()
{
return new RdKafkaTopic(self::EXPECTED_TOPIC_NAME);
diff --git a/pkg/rdkafka/Tests/bootstrap.php b/pkg/rdkafka/Tests/bootstrap.php
index bf112623e..60f8101ef 100644
--- a/pkg/rdkafka/Tests/bootstrap.php
+++ b/pkg/rdkafka/Tests/bootstrap.php
@@ -8,7 +8,7 @@
if (false == file_exists($kafkaStubsDir)) {
$kafkaStubsDir = __DIR__.'/../../../vendor/kwn/php-rdkafka-stubs';
if (false == file_exists($kafkaStubsDir)) {
- throw new \LogicException('The kafka extension is not loaded and stubs could not be found as well');
+ throw new LogicException('The kafka extension is not loaded and stubs could not be found as well');
}
}
diff --git a/pkg/rdkafka/Tests/fix_composer_json.php b/pkg/rdkafka/Tests/fix_composer_json.php
deleted file mode 100644
index b778f6f69..000000000
--- a/pkg/rdkafka/Tests/fix_composer_json.php
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
+
diff --git a/pkg/redis/.gitattributes b/pkg/redis/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/redis/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/redis/.github/workflows/ci.yml b/pkg/redis/.github/workflows/ci.yml
new file mode 100644
index 000000000..e33e0628c
--- /dev/null
+++ b/pkg/redis/.github/workflows/ci.yml
@@ -0,0 +1,30 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+ extensions: redis
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/redis/.travis.yml b/pkg/redis/.travis.yml
deleted file mode 100644
index 9ed4fa123..000000000
--- a/pkg/redis/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-sudo: false
-
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
- - '7.2'
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - composer self-update
- - composer install --prefer-source
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/redis/JsonSerializer.php b/pkg/redis/JsonSerializer.php
new file mode 100644
index 000000000..ff67ed880
--- /dev/null
+++ b/pkg/redis/JsonSerializer.php
@@ -0,0 +1,33 @@
+ $message->getBody(),
+ 'properties' => $message->getProperties(),
+ 'headers' => $message->getHeaders(),
+ ]);
+
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
+ }
+
+ return $json;
+ }
+
+ public function toMessage(string $string): RedisMessage
+ {
+ $data = json_decode($string, true);
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
+ }
+
+ return new RedisMessage($data['body'], $data['properties'], $data['headers']);
+ }
+}
diff --git a/pkg/redis/LuaScripts.php b/pkg/redis/LuaScripts.php
new file mode 100644
index 000000000..4a40d2447
--- /dev/null
+++ b/pkg/redis/LuaScripts.php
@@ -0,0 +1,38 @@
+options = $config['predis_options'];
$this->parameters = [
@@ -37,6 +41,7 @@ public function __construct(array $config)
'host' => $config['host'],
'port' => $config['port'],
'password' => $config['password'],
+ 'database' => $config['database'],
'path' => $config['path'],
'async' => $config['async'],
'persistent' => $config['persistent'],
@@ -49,12 +54,40 @@ public function __construct(array $config)
}
}
+ public function eval(string $script, array $keys = [], array $args = [])
+ {
+ try {
+ // mixed eval($script, $numkeys, $keyOrArg1 = null, $keyOrArgN = null)
+ return call_user_func_array([$this->redis, 'eval'], array_merge([$script, count($keys)], $keys, $args));
+ } catch (PRedisServerException $e) {
+ throw new ServerException('eval command has failed', 0, $e);
+ }
+ }
+
+ public function zadd(string $key, string $value, float $score): int
+ {
+ try {
+ return $this->redis->zadd($key, [$value => $score]);
+ } catch (PRedisServerException $e) {
+ throw new ServerException('zadd command has failed', 0, $e);
+ }
+ }
+
+ public function zrem(string $key, string $value): int
+ {
+ try {
+ return $this->redis->zrem($key, [$value]);
+ } catch (PRedisServerException $e) {
+ throw new ServerException('zrem command has failed', 0, $e);
+ }
+ }
+
public function lpush(string $key, string $value): int
{
try {
return $this->redis->lpush($key, [$value]);
} catch (PRedisServerException $e) {
- throw new ServerException('lpush command has failed', null, $e);
+ throw new ServerException('lpush command has failed', 0, $e);
}
}
@@ -67,7 +100,7 @@ public function brpop(array $keys, int $timeout): ?RedisResult
return null;
} catch (PRedisServerException $e) {
- throw new ServerException('brpop command has failed', null, $e);
+ throw new ServerException('brpop command has failed', 0, $e);
}
}
@@ -80,7 +113,7 @@ public function rpop(string $key): ?RedisResult
return null;
} catch (PRedisServerException $e) {
- throw new ServerException('rpop command has failed', null, $e);
+ throw new ServerException('rpop command has failed', 0, $e);
}
}
diff --git a/pkg/redis/PhpRedis.php b/pkg/redis/PhpRedis.php
index 68652e6b6..9e820a283 100644
--- a/pkg/redis/PhpRedis.php
+++ b/pkg/redis/PhpRedis.php
@@ -19,15 +19,46 @@ class PhpRedis implements Redis
*/
public function __construct(array $config)
{
+ if (false == class_exists(\Redis::class)) {
+ throw new \LogicException('You must install the redis extension to use phpredis');
+ }
+
$this->config = $config;
}
+ public function eval(string $script, array $keys = [], array $args = [])
+ {
+ try {
+ return $this->redis->eval($script, array_merge($keys, $args), count($keys));
+ } catch (\RedisException $e) {
+ throw new ServerException('eval command has failed', 0, $e);
+ }
+ }
+
+ public function zadd(string $key, string $value, float $score): int
+ {
+ try {
+ return $this->redis->zAdd($key, $score, $value);
+ } catch (\RedisException $e) {
+ throw new ServerException('zadd command has failed', 0, $e);
+ }
+ }
+
+ public function zrem(string $key, string $value): int
+ {
+ try {
+ return $this->redis->zRem($key, $value);
+ } catch (\RedisException $e) {
+ throw new ServerException('zrem command has failed', 0, $e);
+ }
+ }
+
public function lpush(string $key, string $value): int
{
try {
return $this->redis->lPush($key, $value);
} catch (\RedisException $e) {
- throw new ServerException('lpush command has failed', null, $e);
+ throw new ServerException('lpush command has failed', 0, $e);
}
}
@@ -40,7 +71,7 @@ public function brpop(array $keys, int $timeout): ?RedisResult
return null;
} catch (\RedisException $e) {
- throw new ServerException('brpop command has failed', null, $e);
+ throw new ServerException('brpop command has failed', 0, $e);
}
}
@@ -53,7 +84,7 @@ public function rpop(string $key): ?RedisResult
return null;
} catch (\RedisException $e) {
- throw new ServerException('rpop command has failed', null, $e);
+ throw new ServerException('rpop command has failed', 0, $e);
}
}
@@ -63,27 +94,25 @@ public function connect(): void
return;
}
- $supportedSchemes = ['redis', 'tcp', 'unix'];
+ $supportedSchemes = ['redis', 'rediss', 'tcp', 'unix'];
if (false == in_array($this->config['scheme'], $supportedSchemes, true)) {
- throw new \LogicException(sprintf(
- 'The given scheme protocol "%s" is not supported by php extension. It must be one of "%s"',
- $this->config['scheme'],
- implode('", "', $supportedSchemes)
- ));
+ throw new \LogicException(sprintf('The given scheme protocol "%s" is not supported by php extension. It must be one of "%s"', $this->config['scheme'], implode('", "', $supportedSchemes)));
}
$this->redis = new \Redis();
$connectionMethod = $this->config['persistent'] ? 'pconnect' : 'connect';
+ $host = 'rediss' === $this->config['scheme'] ? 'tls://'.$this->config['host'] : $this->config['host'];
+
$result = call_user_func(
[$this->redis, $connectionMethod],
- 'unix' === $this->config['scheme'] ? $this->config['path'] : $this->config['host'],
+ 'unix' === $this->config['scheme'] ? $this->config['path'] : $host,
$this->config['port'],
$this->config['timeout'],
$this->config['persistent'] ? ($this->config['phpredis_persistent_id'] ?? null) : null,
- $this->config['phpredis_retry_interval'] ?? null,
- $this->config['read_write_timeout']
+ (int) ($this->config['phpredis_retry_interval'] ?? 0),
+ (float) $this->config['read_write_timeout'] ?? 0
);
if (false == $result) {
diff --git a/pkg/redis/README.md b/pkg/redis/README.md
index 631a4dc05..b0a9b082e 100644
--- a/pkg/redis/README.md
+++ b/pkg/redis/README.md
@@ -1,27 +1,40 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Redis Transport
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/redis)
+[](https://github.com/php-enqueue/redis/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/redis)
[](https://packagist.org/packages/enqueue/redis)
-
-This is an implementation of Queue Interop specification. It allows you to send and consume message with Redis store as a broker.
+
+This is an implementation of Queue Interop specification. It allows you to send and consume message with Redis store as a broker.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/transport/redis/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
-It is released under the [MIT License](LICENSE).
\ No newline at end of file
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/redis/Redis.php b/pkg/redis/Redis.php
index 2ea2e054e..04165af9d 100644
--- a/pkg/redis/Redis.php
+++ b/pkg/redis/Redis.php
@@ -7,9 +7,21 @@
interface Redis
{
/**
- * @param string $key
- * @param string $value
- *
+ * @throws ServerException
+ */
+ public function eval(string $script, array $keys = [], array $args = []);
+
+ /**
+ * @throws ServerException
+ */
+ public function zadd(string $key, string $value, float $score): int;
+
+ /**
+ * @throws ServerException
+ */
+ public function zrem(string $key, string $value): int;
+
+ /**
* @throws ServerException
*
* @return int length of the list
@@ -21,17 +33,11 @@ public function lpush(string $key, string $value): int;
* @param int $timeout in seconds
*
* @throws ServerException
- *
- * @return RedisResult|null
*/
public function brpop(array $keys, int $timeout): ?RedisResult;
/**
- * @param string $key
- *
* @throws ServerException
- *
- * @return RedisResult|null
*/
public function rpop(string $key): ?RedisResult;
@@ -43,8 +49,6 @@ public function connect(): void;
public function disconnect(): void;
/**
- * @param string $key
- *
* @throws ServerException
*/
public function del(string $key): void;
diff --git a/pkg/redis/RedisConnectionFactory.php b/pkg/redis/RedisConnectionFactory.php
index e691810ff..e31a88456 100644
--- a/pkg/redis/RedisConnectionFactory.php
+++ b/pkg/redis/RedisConnectionFactory.php
@@ -38,6 +38,8 @@ class RedisConnectionFactory implements ConnectionFactory
* 'read_write_timeout' => Timeout (expressed in seconds) used when performing read or write operations on the underlying network resource after which an exception is thrown.
* 'predis_options' => An array of predis specific options.
* 'ssl' => could be any of http://fi2.php.net/manual/en/context.ssl.php#refsect1-context.ssl-options
+ * 'redelivery_delay' => Default 300 sec. Returns back message into the queue if message was not acknowledged or rejected after this delay.
+ * It could happen if consumer has failed with fatal error or even if message processing is slow and takes more than this time.
* ].
*
* or
@@ -85,18 +87,16 @@ public function createContext(): Context
if ($this->config['lazy']) {
return new RedisContext(function () {
return $this->createRedis();
- });
+ }, (int) $this->config['redelivery_delay']);
}
- return new RedisContext($this->createRedis());
+ return new RedisContext($this->createRedis(), (int) $this->config['redelivery_delay']);
}
private function createRedis(): Redis
{
if (false == $this->redis) {
- if (in_array('predis', $this->config['scheme_extensions'], true)) {
- $this->redis = new PRedis($this->config);
- } elseif (in_array('phpredis', $this->config['scheme_extensions'], true)) {
+ if (in_array('phpredis', $this->config['scheme_extensions'], true)) {
$this->redis = new PhpRedis($this->config);
} else {
$this->redis = new PRedis($this->config);
@@ -110,18 +110,14 @@ private function createRedis(): Redis
private function parseDsn(string $dsn): array
{
- $dsn = new Dsn($dsn);
+ $dsn = Dsn::parseFirst($dsn);
$supportedSchemes = ['redis', 'rediss', 'tcp', 'tls', 'unix'];
if (false == in_array($dsn->getSchemeProtocol(), $supportedSchemes, true)) {
- throw new \LogicException(sprintf(
- 'The given scheme protocol "%s" is not supported. It must be one of "%s"',
- $dsn->getSchemeProtocol(),
- implode('", "', $supportedSchemes)
- ));
+ throw new \LogicException(sprintf('The given scheme protocol "%s" is not supported. It must be one of "%s"', $dsn->getSchemeProtocol(), implode('", "', $supportedSchemes)));
}
- $database = $dsn->getInt('database');
+ $database = $dsn->getDecimal('database');
// try use path as database name if not set.
if (null === $database && 'unix' !== $dsn->getSchemeProtocol() && null !== $dsn->getPath()) {
@@ -135,7 +131,7 @@ private function parseDsn(string $dsn): array
'port' => $dsn->getPort(),
'path' => $dsn->getPath(),
'database' => $database,
- 'password' => $dsn->getPassword(),
+ 'password' => $dsn->getPassword() ?: $dsn->getUser() ?: $dsn->getString('password'),
'async' => $dsn->getBool('async'),
'persistent' => $dsn->getBool('persistent'),
'timeout' => $dsn->getFloat('timeout'),
@@ -160,6 +156,7 @@ private function defaultConfig(): array
'read_write_timeout' => null,
'predis_options' => null,
'ssl' => null,
+ 'redelivery_delay' => 300,
];
}
}
diff --git a/pkg/redis/RedisConsumer.php b/pkg/redis/RedisConsumer.php
index 0fb9db787..ca3733d4b 100644
--- a/pkg/redis/RedisConsumer.php
+++ b/pkg/redis/RedisConsumer.php
@@ -11,6 +11,8 @@
class RedisConsumer implements Consumer
{
+ use RedisConsumerHelperTrait;
+
/**
* @var RedisDestination
*/
@@ -21,12 +23,27 @@ class RedisConsumer implements Consumer
*/
private $context;
+ /**
+ * @var int
+ */
+ private $redeliveryDelay = 300;
+
public function __construct(RedisContext $context, RedisDestination $queue)
{
$this->context = $context;
$this->queue = $queue;
}
+ public function getRedeliveryDelay(): ?int
+ {
+ return $this->redeliveryDelay;
+ }
+
+ public function setRedeliveryDelay(int $delay): void
+ {
+ $this->redeliveryDelay = $delay;
+ }
+
/**
* @return RedisDestination
*/
@@ -40,8 +57,9 @@ public function getQueue(): Queue
*/
public function receive(int $timeout = 0): ?Message
{
- $timeout = (int) ($timeout / 1000);
- if (empty($timeout)) {
+ $timeout = (int) ceil($timeout / 1000);
+
+ if ($timeout <= 0) {
while (true) {
if ($message = $this->receive(5000)) {
return $message;
@@ -49,11 +67,7 @@ public function receive(int $timeout = 0): ?Message
}
}
- if ($result = $this->getRedis()->brpop([$this->queue->getName()], $timeout)) {
- return RedisMessage::jsonUnserialize($result->getMessage());
- }
-
- return null;
+ return $this->receiveMessage([$this->queue], $timeout, $this->redeliveryDelay);
}
/**
@@ -61,11 +75,7 @@ public function receive(int $timeout = 0): ?Message
*/
public function receiveNoWait(): ?Message
{
- if ($result = $this->getRedis()->rpop($this->queue->getName())) {
- return RedisMessage::jsonUnserialize($result->getMessage());
- }
-
- return null;
+ return $this->receiveMessageNoWait($this->queue, $this->redeliveryDelay);
}
/**
@@ -73,7 +83,7 @@ public function receiveNoWait(): ?Message
*/
public function acknowledge(Message $message): void
{
- // do nothing. redis transport always works in auto ack mode
+ $this->getRedis()->zrem($this->queue->getName().':reserved', $message->getReservedKey());
}
/**
@@ -83,13 +93,27 @@ public function reject(Message $message, bool $requeue = false): void
{
InvalidMessageException::assertMessageInstanceOf($message, RedisMessage::class);
- // do nothing on reject. redis transport always works in auto ack mode
+ $this->acknowledge($message);
if ($requeue) {
- $this->context->createProducer()->send($this->queue, $message);
+ $message = $this->getContext()->getSerializer()->toMessage($message->getReservedKey());
+ $message->setRedelivered(true);
+
+ if ($message->getTimeToLive()) {
+ $message->setHeader('expires_at', time() + $message->getTimeToLive());
+ }
+
+ $payload = $this->getContext()->getSerializer()->toString($message);
+
+ $this->getRedis()->lpush($this->queue->getName(), $payload);
}
}
+ private function getContext(): RedisContext
+ {
+ return $this->context;
+ }
+
private function getRedis(): Redis
{
return $this->context->getRedis();
diff --git a/pkg/redis/RedisConsumerHelperTrait.php b/pkg/redis/RedisConsumerHelperTrait.php
new file mode 100644
index 000000000..063ff1fbd
--- /dev/null
+++ b/pkg/redis/RedisConsumerHelperTrait.php
@@ -0,0 +1,114 @@
+queueNames) {
+ $this->queueNames = [];
+ foreach ($queues as $queue) {
+ $this->queueNames[] = $queue->getName();
+ }
+ }
+
+ while ($thisTimeout > 0) {
+ $this->migrateExpiredMessages($this->queueNames);
+
+ if (false == $result = $this->getContext()->getRedis()->brpop($this->queueNames, $thisTimeout)) {
+ return null;
+ }
+
+ $this->pushQueueNameBack($result->getKey());
+
+ if ($message = $this->processResult($result, $redeliveryDelay)) {
+ return $message;
+ }
+
+ $thisTimeout -= time() - $startAt;
+ }
+
+ return null;
+ }
+
+ protected function receiveMessageNoWait(RedisDestination $destination, int $redeliveryDelay): ?RedisMessage
+ {
+ $this->migrateExpiredMessages([$destination->getName()]);
+
+ if ($result = $this->getContext()->getRedis()->rpop($destination->getName())) {
+ return $this->processResult($result, $redeliveryDelay);
+ }
+
+ return null;
+ }
+
+ protected function processResult(RedisResult $result, int $redeliveryDelay): ?RedisMessage
+ {
+ $message = $this->getContext()->getSerializer()->toMessage($result->getMessage());
+
+ $now = time();
+
+ if (0 === $message->getAttempts() && $expiresAt = $message->getHeader('expires_at')) {
+ if ($now > $expiresAt) {
+ return null;
+ }
+ }
+
+ $message->setHeader('attempts', $message->getAttempts() + 1);
+ $message->setRedelivered($message->getAttempts() > 1);
+ $message->setKey($result->getKey());
+ $message->setReservedKey($this->getContext()->getSerializer()->toString($message));
+
+ $reservedQueue = $result->getKey().':reserved';
+ $redeliveryAt = $now + $redeliveryDelay;
+
+ $this->getContext()->getRedis()->zadd($reservedQueue, $message->getReservedKey(), $redeliveryAt);
+
+ return $message;
+ }
+
+ protected function pushQueueNameBack(string $queueName): void
+ {
+ if (count($this->queueNames) <= 1) {
+ return;
+ }
+
+ if (false === $from = array_search($queueName, $this->queueNames, true)) {
+ throw new \LogicException(sprintf('Queue name was not found: "%s"', $queueName));
+ }
+
+ $to = count($this->queueNames) - 1;
+
+ $out = array_splice($this->queueNames, $from, 1);
+ array_splice($this->queueNames, $to, 0, $out);
+ }
+
+ protected function migrateExpiredMessages(array $queueNames): void
+ {
+ $now = time();
+
+ foreach ($queueNames as $queueName) {
+ $this->getContext()->getRedis()
+ ->eval(LuaScripts::migrateExpired(), [$queueName.':delayed', $queueName], [$now]);
+
+ $this->getContext()->getRedis()
+ ->eval(LuaScripts::migrateExpired(), [$queueName.':reserved', $queueName], [$now]);
+ }
+ }
+}
diff --git a/pkg/redis/RedisContext.php b/pkg/redis/RedisContext.php
index e69385884..346375f8d 100644
--- a/pkg/redis/RedisContext.php
+++ b/pkg/redis/RedisContext.php
@@ -17,6 +17,8 @@
class RedisContext implements Context
{
+ use SerializerAwareTrait;
+
/**
* @var Redis
*/
@@ -27,24 +29,28 @@ class RedisContext implements Context
*/
private $redisFactory;
+ /**
+ * @var int
+ */
+ private $redeliveryDelay = 300;
+
/**
* Callable must return instance of Redis once called.
*
* @param Redis|callable $redis
*/
- public function __construct($redis)
+ public function __construct($redis, int $redeliveryDelay)
{
if ($redis instanceof Redis) {
$this->redis = $redis;
} elseif (is_callable($redis)) {
$this->redisFactory = $redis;
} else {
- throw new \InvalidArgumentException(sprintf(
- 'The $redis argument must be either %s or callable that returns %s once called.',
- Redis::class,
- Redis::class
- ));
+ throw new \InvalidArgumentException(sprintf('The $redis argument must be either %s or callable that returns %s once called.', Redis::class, Redis::class));
}
+
+ $this->redeliveryDelay = $redeliveryDelay;
+ $this->setSerializer(new JsonSerializer());
}
/**
@@ -78,7 +84,7 @@ public function deleteQueue(Queue $queue): void
{
InvalidDestinationException::assertDestinationInstanceOf($queue, RedisDestination::class);
- $this->getRedis()->del($queue->getName());
+ $this->deleteDestination($queue);
}
/**
@@ -88,7 +94,7 @@ public function deleteTopic(Topic $topic): void
{
InvalidDestinationException::assertDestinationInstanceOf($topic, RedisDestination::class);
- $this->getRedis()->del($topic->getName());
+ $this->deleteDestination($topic);
}
public function createTemporaryQueue(): Queue
@@ -101,7 +107,7 @@ public function createTemporaryQueue(): Queue
*/
public function createProducer(): Producer
{
- return new RedisProducer($this->getRedis());
+ return new RedisProducer($this);
}
/**
@@ -113,7 +119,10 @@ public function createConsumer(Destination $destination): Consumer
{
InvalidDestinationException::assertDestinationInstanceOf($destination, RedisDestination::class);
- return new RedisConsumer($this, $destination);
+ $consumer = new RedisConsumer($this, $destination);
+ $consumer->setRedeliveryDelay($this->redeliveryDelay);
+
+ return $consumer;
}
/**
@@ -121,7 +130,10 @@ public function createConsumer(Destination $destination): Consumer
*/
public function createSubscriptionConsumer(): SubscriptionConsumer
{
- return new RedisSubscriptionConsumer($this);
+ $consumer = new RedisSubscriptionConsumer($this);
+ $consumer->setRedeliveryDelay($this->redeliveryDelay);
+
+ return $consumer;
}
/**
@@ -129,7 +141,7 @@ public function createSubscriptionConsumer(): SubscriptionConsumer
*/
public function purgeQueue(Queue $queue): void
{
- $this->getRedis()->del($queue->getName());
+ $this->deleteDestination($queue);
}
public function close(): void
@@ -142,11 +154,7 @@ public function getRedis(): Redis
if (false == $this->redis) {
$redis = call_user_func($this->redisFactory);
if (false == $redis instanceof Redis) {
- throw new \LogicException(sprintf(
- 'The factory must return instance of %s. It returned %s',
- Redis::class,
- is_object($redis) ? get_class($redis) : gettype($redis)
- ));
+ throw new \LogicException(sprintf('The factory must return instance of %s. It returned %s', Redis::class, is_object($redis) ? $redis::class : gettype($redis)));
}
$this->redis = $redis;
@@ -154,4 +162,11 @@ public function getRedis(): Redis
return $this->redis;
}
+
+ private function deleteDestination(RedisDestination $destination): void
+ {
+ $this->getRedis()->del($destination->getName());
+ $this->getRedis()->del($destination->getName().':delayed');
+ $this->getRedis()->del($destination->getName().':reserved');
+ }
}
diff --git a/pkg/redis/RedisMessage.php b/pkg/redis/RedisMessage.php
index ab614f773..708bdbc97 100644
--- a/pkg/redis/RedisMessage.php
+++ b/pkg/redis/RedisMessage.php
@@ -6,7 +6,7 @@
use Interop\Queue\Message;
-class RedisMessage implements Message, \JsonSerializable
+class RedisMessage implements Message
{
/**
* @var string
@@ -28,6 +28,16 @@ class RedisMessage implements Message, \JsonSerializable
*/
private $redelivered;
+ /**
+ * @var string
+ */
+ private $reservedKey;
+
+ /**
+ * @var string
+ */
+ private $key;
+
public function __construct(string $body = '', array $properties = [], array $headers = [])
{
$this->body = $body;
@@ -97,7 +107,7 @@ public function isRedelivered(): bool
return $this->redelivered;
}
- public function setCorrelationId(string $correlationId = null): void
+ public function setCorrelationId(?string $correlationId = null): void
{
$this->setHeader('correlation_id', $correlationId);
}
@@ -107,7 +117,7 @@ public function getCorrelationId(): ?string
return $this->getHeader('correlation_id');
}
- public function setMessageId(string $messageId = null): void
+ public function setMessageId(?string $messageId = null): void
{
$this->setHeader('message_id', $messageId);
}
@@ -124,12 +134,12 @@ public function getTimestamp(): ?int
return null === $value ? null : (int) $value;
}
- public function setTimestamp(int $timestamp = null): void
+ public function setTimestamp(?int $timestamp = null): void
{
$this->setHeader('timestamp', $timestamp);
}
- public function setReplyTo(string $replyTo = null): void
+ public function setReplyTo(?string $replyTo = null): void
{
$this->setHeader('reply_to', $replyTo);
}
@@ -139,26 +149,54 @@ public function getReplyTo(): ?string
return $this->getHeader('reply_to');
}
- public function jsonSerialize(): array
+ public function getAttempts(): int
+ {
+ return (int) $this->getHeader('attempts', 0);
+ }
+
+ public function getTimeToLive(): ?int
+ {
+ return $this->getHeader('time_to_live');
+ }
+
+ /**
+ * Set time to live in milliseconds.
+ */
+ public function setTimeToLive(?int $timeToLive = null): void
+ {
+ $this->setHeader('time_to_live', $timeToLive);
+ }
+
+ public function getDeliveryDelay(): ?int
+ {
+ return $this->getHeader('delivery_delay');
+ }
+
+ /**
+ * Set delay in milliseconds.
+ */
+ public function setDeliveryDelay(?int $deliveryDelay = null): void
+ {
+ $this->setHeader('delivery_delay', $deliveryDelay);
+ }
+
+ public function getReservedKey(): ?string
+ {
+ return $this->reservedKey;
+ }
+
+ public function setReservedKey(string $reservedKey)
{
- return [
- 'body' => $this->getBody(),
- 'properties' => $this->getProperties(),
- 'headers' => $this->getHeaders(),
- ];
+ $this->reservedKey = $reservedKey;
}
- public static function jsonUnserialize(string $json): self
+ public function getKey(): ?string
{
- $data = json_decode($json, true);
- if (JSON_ERROR_NONE !== json_last_error()) {
- throw new \InvalidArgumentException(sprintf(
- 'The malformed json given. Error %s and message %s',
- json_last_error(),
- json_last_error_msg()
- ));
- }
+ return $this->key;
+ }
- return new self($data['body'], $data['properties'], $data['headers']);
+ public function setKey(string $key): void
+ {
+ $this->key = $key;
}
}
diff --git a/pkg/redis/RedisProducer.php b/pkg/redis/RedisProducer.php
index 81ca13b7e..3ad3e5bb2 100644
--- a/pkg/redis/RedisProducer.php
+++ b/pkg/redis/RedisProducer.php
@@ -7,22 +7,31 @@
use Interop\Queue\Destination;
use Interop\Queue\Exception\InvalidDestinationException;
use Interop\Queue\Exception\InvalidMessageException;
+use Interop\Queue\Exception\PriorityNotSupportedException;
use Interop\Queue\Message;
use Interop\Queue\Producer;
+use Ramsey\Uuid\Uuid;
class RedisProducer implements Producer
{
/**
- * @var Redis
+ * @var RedisContext
*/
- private $redis;
+ private $context;
/**
- * @param Redis $redis
+ * @var int|null
*/
- public function __construct(Redis $redis)
+ private $timeToLive;
+
+ /**
+ * @var int
+ */
+ private $deliveryDelay;
+
+ public function __construct(RedisContext $context)
{
- $this->redis = $redis;
+ $this->context = $context;
}
/**
@@ -34,36 +43,56 @@ public function send(Destination $destination, Message $message): void
InvalidDestinationException::assertDestinationInstanceOf($destination, RedisDestination::class);
InvalidMessageException::assertMessageInstanceOf($message, RedisMessage::class);
- $this->redis->lpush($destination->getName(), json_encode($message));
+ $message->setMessageId(Uuid::uuid4()->toString());
+ $message->setHeader('attempts', 0);
+
+ if (null !== $this->timeToLive && null === $message->getTimeToLive()) {
+ $message->setTimeToLive($this->timeToLive);
+ }
+
+ if (null !== $this->deliveryDelay && null === $message->getDeliveryDelay()) {
+ $message->setDeliveryDelay($this->deliveryDelay);
+ }
+
+ if ($message->getTimeToLive()) {
+ $message->setHeader('expires_at', time() + $message->getTimeToLive());
+ }
+
+ $payload = $this->context->getSerializer()->toString($message);
+
+ if ($message->getDeliveryDelay()) {
+ $deliveryAt = time() + $message->getDeliveryDelay() / 1000;
+ $this->context->getRedis()->zadd($destination->getName().':delayed', $payload, $deliveryAt);
+ } else {
+ $this->context->getRedis()->lpush($destination->getName(), $payload);
+ }
}
/**
- * @return RedisProducer
+ * @return self
*/
- public function setDeliveryDelay(int $deliveryDelay = null): Producer
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
{
- if (null === $deliveryDelay) {
- return $this;
- }
+ $this->deliveryDelay = $deliveryDelay;
- throw new \LogicException('Not implemented');
+ return $this;
}
public function getDeliveryDelay(): ?int
{
- return null;
+ return $this->deliveryDelay;
}
/**
* @return RedisProducer
*/
- public function setPriority(int $priority = null): Producer
+ public function setPriority(?int $priority = null): Producer
{
if (null === $priority) {
return $this;
}
- throw new \LogicException('Not implemented');
+ throw PriorityNotSupportedException::providerDoestNotSupportIt();
}
public function getPriority(): ?int
@@ -72,19 +101,17 @@ public function getPriority(): ?int
}
/**
- * @return RedisProducer
+ * @return self
*/
- public function setTimeToLive(int $timeToLive = null): Producer
+ public function setTimeToLive(?int $timeToLive = null): Producer
{
- if (null === $timeToLive) {
- return $this;
- }
+ $this->timeToLive = $timeToLive;
- throw new \LogicException('Not implemented');
+ return $this;
}
public function getTimeToLive(): ?int
{
- return null;
+ return $this->timeToLive;
}
}
diff --git a/pkg/redis/RedisSubscriptionConsumer.php b/pkg/redis/RedisSubscriptionConsumer.php
index 1b6cd1149..d0b34634d 100644
--- a/pkg/redis/RedisSubscriptionConsumer.php
+++ b/pkg/redis/RedisSubscriptionConsumer.php
@@ -9,6 +9,8 @@
class RedisSubscriptionConsumer implements SubscriptionConsumer
{
+ use RedisConsumerHelperTrait;
+
/**
* @var RedisContext
*/
@@ -22,14 +24,26 @@ class RedisSubscriptionConsumer implements SubscriptionConsumer
private $subscribers;
/**
- * @param RedisContext $context
+ * @var int
*/
+ private $redeliveryDelay = 300;
+
public function __construct(RedisContext $context)
{
$this->context = $context;
$this->subscribers = [];
}
+ public function getRedeliveryDelay(): ?int
+ {
+ return $this->redeliveryDelay;
+ }
+
+ public function setRedeliveryDelay(int $delay): void
+ {
+ $this->redeliveryDelay = $delay;
+ }
+
public function consume(int $timeout = 0): void
{
if (empty($this->subscribers)) {
@@ -39,32 +53,19 @@ public function consume(int $timeout = 0): void
$timeout = (int) ceil($timeout / 1000);
$endAt = time() + $timeout;
- $queueNames = [];
- foreach (array_keys($this->subscribers) as $queueName) {
- $queueNames[$queueName] = $queueName;
+ $queues = [];
+ /** @var Consumer $consumer */
+ foreach ($this->subscribers as list($consumer)) {
+ $queues[] = $consumer->getQueue();
}
- $currentQueueNames = [];
while (true) {
- if (empty($currentQueueNames)) {
- $currentQueueNames = $queueNames;
- }
+ if ($message = $this->receiveMessage($queues, $timeout ?: 5, $this->redeliveryDelay)) {
+ list($consumer, $callback) = $this->subscribers[$message->getKey()];
- $result = $this->context->getRedis()->brpop($currentQueueNames, $timeout ?: 5);
- if ($result) {
- $message = RedisMessage::jsonUnserialize($result->getMessage());
- list($consumer, $callback) = $this->subscribers[$result->getKey()];
if (false === call_user_func($callback, $message, $consumer)) {
return;
}
-
- unset($currentQueueNames[$result->getKey()]);
- } else {
- $currentQueueNames = [];
-
- if ($timeout && microtime(true) >= $endAt) {
- return;
- }
}
if ($timeout && microtime(true) >= $endAt) {
@@ -79,7 +80,7 @@ public function consume(int $timeout = 0): void
public function subscribe(Consumer $consumer, callable $callback): void
{
if (false == $consumer instanceof RedisConsumer) {
- throw new \InvalidArgumentException(sprintf('The consumer must be instance of "%s" got "%s"', RedisConsumer::class, get_class($consumer)));
+ throw new \InvalidArgumentException(sprintf('The consumer must be instance of "%s" got "%s"', RedisConsumer::class, $consumer::class));
}
$queueName = $consumer->getQueue()->getQueueName();
@@ -92,6 +93,7 @@ public function subscribe(Consumer $consumer, callable $callback): void
}
$this->subscribers[$queueName] = [$consumer, $callback];
+ $this->queueNames = null;
}
/**
@@ -100,7 +102,7 @@ public function subscribe(Consumer $consumer, callable $callback): void
public function unsubscribe(Consumer $consumer): void
{
if (false == $consumer instanceof RedisConsumer) {
- throw new \InvalidArgumentException(sprintf('The consumer must be instance of "%s" got "%s"', RedisConsumer::class, get_class($consumer)));
+ throw new \InvalidArgumentException(sprintf('The consumer must be instance of "%s" got "%s"', RedisConsumer::class, $consumer::class));
}
$queueName = $consumer->getQueue()->getQueueName();
@@ -114,10 +116,17 @@ public function unsubscribe(Consumer $consumer): void
}
unset($this->subscribers[$queueName]);
+ $this->queueNames = null;
}
public function unsubscribeAll(): void
{
$this->subscribers = [];
+ $this->queueNames = null;
+ }
+
+ private function getContext(): RedisContext
+ {
+ return $this->context;
}
}
diff --git a/pkg/redis/Serializer.php b/pkg/redis/Serializer.php
new file mode 100644
index 000000000..a936a9328
--- /dev/null
+++ b/pkg/redis/Serializer.php
@@ -0,0 +1,12 @@
+serializer = $serializer;
+ }
+
+ /**
+ * @return Serializer
+ */
+ public function getSerializer()
+ {
+ return $this->serializer;
+ }
+}
diff --git a/pkg/redis/Tests/Functional/CommonUseCasesTrait.php b/pkg/redis/Tests/Functional/CommonUseCasesTrait.php
index 02f63d6f4..bdab87b31 100644
--- a/pkg/redis/Tests/Functional/CommonUseCasesTrait.php
+++ b/pkg/redis/Tests/Functional/CommonUseCasesTrait.php
@@ -61,7 +61,10 @@ public function testProduceAndReceiveOneMessageSentDirectlyToQueue()
$this->assertEquals(__METHOD__, $message->getBody());
$this->assertEquals(['FooProperty' => 'FooVal'], $message->getProperties());
- $this->assertEquals(['BarHeader' => 'BarVal'], $message->getHeaders());
+ $this->assertCount(3, $message->getHeaders());
+ $this->assertSame(1, $message->getHeader('attempts'));
+ $this->assertSame('BarVal', $message->getHeader('BarHeader'));
+ $this->assertNotEmpty('BarVal', $message->getHeader('message_id'));
}
public function testProduceAndReceiveOneMessageSentDirectlyToTopic()
@@ -88,7 +91,7 @@ public function testConsumerReceiveMessageWithZeroTimeout()
$consumer = $this->getContext()->createConsumer($topic);
- //guard
+ // guard
$this->assertNull($consumer->receive(1000));
$message = $this->getContext()->createMessage(__METHOD__);
@@ -99,7 +102,7 @@ public function testConsumerReceiveMessageWithZeroTimeout()
$actualMessage = $consumer->receive(0);
$this->assertInstanceOf(RedisMessage::class, $actualMessage);
- $consumer->acknowledge($message);
+ $consumer->acknowledge($actualMessage);
$this->assertEquals(__METHOD__, $message->getBody());
}
diff --git a/pkg/redis/Tests/Functional/PRedisCommonUseCasesTest.php b/pkg/redis/Tests/Functional/PRedisCommonUseCasesTest.php
index 8c95e47de..9ac2a037b 100644
--- a/pkg/redis/Tests/Functional/PRedisCommonUseCasesTest.php
+++ b/pkg/redis/Tests/Functional/PRedisCommonUseCasesTest.php
@@ -11,15 +11,15 @@
*/
class PRedisCommonUseCasesTest extends TestCase
{
- use RedisExtension;
use CommonUseCasesTrait;
+ use RedisExtension;
/**
* @var RedisContext
*/
private $context;
- public function setUp()
+ protected function setUp(): void
{
$this->context = $this->buildPRedisContext();
@@ -27,14 +27,11 @@ public function setUp()
$this->context->deleteTopic($this->context->createTopic('enqueue.test_topic'));
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->context->close();
}
- /**
- * {@inheritdoc}
- */
protected function getContext()
{
return $this->context;
diff --git a/pkg/redis/Tests/Functional/PRedisConsumptionUseCasesTest.php b/pkg/redis/Tests/Functional/PRedisConsumptionUseCasesTest.php
index 87fca37fd..e61cd1f0f 100644
--- a/pkg/redis/Tests/Functional/PRedisConsumptionUseCasesTest.php
+++ b/pkg/redis/Tests/Functional/PRedisConsumptionUseCasesTest.php
@@ -11,15 +11,15 @@
*/
class PRedisConsumptionUseCasesTest extends TestCase
{
- use RedisExtension;
use ConsumptionUseCasesTrait;
+ use RedisExtension;
/**
* @var RedisContext
*/
private $context;
- public function setUp()
+ protected function setUp(): void
{
$this->context = $this->buildPRedisContext();
@@ -27,14 +27,11 @@ public function setUp()
$this->context->deleteQueue($this->context->createQueue('enqueue.test_queue_reply'));
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->context->close();
}
- /**
- * {@inheritdoc}
- */
protected function getContext()
{
return $this->context;
diff --git a/pkg/redis/Tests/Functional/PhpRedisCommonUseCasesTest.php b/pkg/redis/Tests/Functional/PhpRedisCommonUseCasesTest.php
index 2d5559d34..f36843ec9 100644
--- a/pkg/redis/Tests/Functional/PhpRedisCommonUseCasesTest.php
+++ b/pkg/redis/Tests/Functional/PhpRedisCommonUseCasesTest.php
@@ -11,15 +11,15 @@
*/
class PhpRedisCommonUseCasesTest extends TestCase
{
- use RedisExtension;
use CommonUseCasesTrait;
+ use RedisExtension;
/**
* @var RedisContext
*/
private $context;
- public function setUp()
+ protected function setUp(): void
{
$this->context = $this->buildPhpRedisContext();
@@ -27,14 +27,11 @@ public function setUp()
$this->context->deleteTopic($this->context->createTopic('enqueue.test_topic'));
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->context->close();
}
- /**
- * {@inheritdoc}
- */
protected function getContext()
{
return $this->context;
diff --git a/pkg/redis/Tests/Functional/PhpRedisConsumptionUseCasesTest.php b/pkg/redis/Tests/Functional/PhpRedisConsumptionUseCasesTest.php
index 50c639f92..073c1aff9 100644
--- a/pkg/redis/Tests/Functional/PhpRedisConsumptionUseCasesTest.php
+++ b/pkg/redis/Tests/Functional/PhpRedisConsumptionUseCasesTest.php
@@ -11,15 +11,15 @@
*/
class PhpRedisConsumptionUseCasesTest extends TestCase
{
- use RedisExtension;
use ConsumptionUseCasesTrait;
+ use RedisExtension;
/**
* @var RedisContext
*/
private $context;
- public function setUp()
+ protected function setUp(): void
{
$this->context = $this->buildPhpRedisContext();
@@ -27,14 +27,11 @@ public function setUp()
$this->context->deleteQueue($this->context->createQueue('enqueue.test_queue_reply'));
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->context->close();
}
- /**
- * {@inheritdoc}
- */
protected function getContext()
{
return $this->context;
diff --git a/pkg/redis/Tests/RedisConnectionFactoryConfigTest.php b/pkg/redis/Tests/RedisConnectionFactoryConfigTest.php
index 953006af9..37e831823 100644
--- a/pkg/redis/Tests/RedisConnectionFactoryConfigTest.php
+++ b/pkg/redis/Tests/RedisConnectionFactoryConfigTest.php
@@ -5,6 +5,7 @@
use Enqueue\Redis\Redis;
use Enqueue\Redis\RedisConnectionFactory;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use PHPUnit\Framework\TestCase;
/**
@@ -13,6 +14,7 @@
class RedisConnectionFactoryConfigTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testThrowNeitherArrayStringNorNullGivenAsConfig()
{
@@ -49,20 +51,8 @@ public function testCouldBeCreatedWithRedisInstance()
$this->assertSame($redisMock, $context->getRedis());
}
- public function testThrowIfRedissConnectionUsedWithPhpRedisExtension()
- {
- $factory = new RedisConnectionFactory('rediss+phpredis:?lazy=0');
-
- $this->expectException(\LogicException::class);
- $this->expectExceptionMessage('The given scheme protocol "rediss" is not supported by php extension. It must be one of "redis", "tcp", "unix"');
- $factory->createContext();
- }
-
/**
* @dataProvider provideConfigs
- *
- * @param mixed $config
- * @param mixed $expectedConfig
*/
public function testShouldParseConfigurationAsExpected($config, $expectedConfig)
{
@@ -90,6 +80,7 @@ public static function provideConfigs()
'read_write_timeout' => null,
'predis_options' => null,
'ssl' => null,
+ 'redelivery_delay' => 300,
],
];
@@ -110,6 +101,7 @@ public static function provideConfigs()
'read_write_timeout' => null,
'predis_options' => null,
'ssl' => null,
+ 'redelivery_delay' => 300,
],
];
@@ -130,6 +122,7 @@ public static function provideConfigs()
'read_write_timeout' => null,
'predis_options' => null,
'ssl' => null,
+ 'redelivery_delay' => 300,
],
];
@@ -151,6 +144,7 @@ public static function provideConfigs()
'predis_options' => null,
'ssl' => null,
'foo' => 'bar',
+ 'redelivery_delay' => 300,
],
];
@@ -172,6 +166,7 @@ public static function provideConfigs()
'predis_options' => null,
'ssl' => null,
'foo' => 'bar',
+ 'redelivery_delay' => 300,
],
];
@@ -193,10 +188,11 @@ public static function provideConfigs()
'predis_options' => null,
'ssl' => null,
'foo' => 'bar',
+ 'redelivery_delay' => 300,
],
];
- //check normal redis connection for php redis extension
+ // check normal redis connection for php redis extension
yield [
'redis+phpredis://localhost:1234?foo=bar',
[
@@ -215,10 +211,11 @@ public static function provideConfigs()
'predis_options' => null,
'ssl' => null,
'foo' => 'bar',
+ 'redelivery_delay' => 300,
],
];
- //check normal redis connection for predis library
+ // check normal redis connection for predis library
yield [
'redis+predis://localhost:1234?foo=bar',
[
@@ -237,10 +234,11 @@ public static function provideConfigs()
'predis_options' => null,
'ssl' => null,
'foo' => 'bar',
+ 'redelivery_delay' => 300,
],
];
- //check tls connection for predis library
+ // check tls connection for predis library
yield [
'rediss+predis://localhost:1234?foo=bar&async=1',
[
@@ -259,6 +257,30 @@ public static function provideConfigs()
'predis_options' => null,
'ssl' => null,
'foo' => 'bar',
+ 'redelivery_delay' => 300,
+ ],
+ ];
+
+ // check tls connection for predis library
+ yield [
+ 'rediss+phpredis://localhost:1234?foo=bar&async=1',
+ [
+ 'host' => 'localhost',
+ 'scheme' => 'rediss',
+ 'port' => 1234,
+ 'timeout' => 5.,
+ 'database' => null,
+ 'password' => null,
+ 'scheme_extensions' => ['phpredis'],
+ 'path' => null,
+ 'async' => true,
+ 'persistent' => false,
+ 'lazy' => true,
+ 'read_write_timeout' => null,
+ 'predis_options' => null,
+ 'ssl' => null,
+ 'foo' => 'bar',
+ 'redelivery_delay' => 300,
],
];
@@ -280,6 +302,7 @@ public static function provideConfigs()
'predis_options' => null,
'ssl' => null,
'foo' => 'bar',
+ 'redelivery_delay' => 300,
],
];
@@ -301,11 +324,55 @@ public static function provideConfigs()
'read_write_timeout' => null,
'predis_options' => null,
'ssl' => null,
+ 'redelivery_delay' => 300,
],
];
- // from predis doc
+ // password as user
+ yield [
+ 'redis://asdfqwer1234asdf@foo',
+ [
+ 'host' => 'foo',
+ 'scheme' => 'redis',
+ 'port' => 6379,
+ 'timeout' => 5.,
+ 'database' => null,
+ 'password' => 'asdfqwer1234asdf',
+ 'scheme_extensions' => [],
+ 'path' => null,
+ 'async' => false,
+ 'persistent' => false,
+ 'lazy' => true,
+ 'read_write_timeout' => null,
+ 'predis_options' => null,
+ 'ssl' => null,
+ 'redelivery_delay' => 300,
+ ],
+ ];
+ // password as query parameter
+ yield [
+ 'redis:?password=asdfqwer1234asdf',
+ [
+ 'host' => '127.0.0.1',
+ 'scheme' => 'redis',
+ 'port' => 6379,
+ 'timeout' => 5.,
+ 'database' => null,
+ 'password' => 'asdfqwer1234asdf',
+ 'scheme_extensions' => [],
+ 'path' => null,
+ 'async' => false,
+ 'persistent' => false,
+ 'lazy' => true,
+ 'read_write_timeout' => null,
+ 'predis_options' => null,
+ 'ssl' => null,
+ 'redelivery_delay' => 300,
+ ],
+ ];
+
+ // from predis doc
yield [
'tls://127.0.0.1?ssl[cafile]=private.pem&ssl[verify_peer]=1',
[
@@ -326,6 +393,7 @@ public static function provideConfigs()
'cafile' => 'private.pem',
'verify_peer' => '1',
],
+ 'redelivery_delay' => 300,
],
];
}
diff --git a/pkg/redis/Tests/RedisConnectionFactoryTest.php b/pkg/redis/Tests/RedisConnectionFactoryTest.php
index 049feaef9..1f9b3a259 100644
--- a/pkg/redis/Tests/RedisConnectionFactoryTest.php
+++ b/pkg/redis/Tests/RedisConnectionFactoryTest.php
@@ -5,12 +5,14 @@
use Enqueue\Redis\RedisConnectionFactory;
use Enqueue\Redis\RedisContext;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use Interop\Queue\ConnectionFactory;
use PHPUnit\Framework\TestCase;
class RedisConnectionFactoryTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testShouldImplementConnectionFactoryInterface()
{
@@ -26,6 +28,6 @@ public function testShouldCreateLazyContext()
$this->assertInstanceOf(RedisContext::class, $context);
$this->assertAttributeEquals(null, 'redis', $context);
- $this->assertInternalType('callable', $this->readAttribute($context, 'redisFactory'));
+ self::assertIsCallable($this->readAttribute($context, 'redisFactory'));
}
}
diff --git a/pkg/redis/Tests/RedisConsumerTest.php b/pkg/redis/Tests/RedisConsumerTest.php
index d8b0c4e7b..56373c18a 100644
--- a/pkg/redis/Tests/RedisConsumerTest.php
+++ b/pkg/redis/Tests/RedisConsumerTest.php
@@ -2,6 +2,7 @@
namespace Enqueue\Redis\Tests;
+use Enqueue\Redis\JsonSerializer;
use Enqueue\Redis\Redis;
use Enqueue\Redis\RedisConsumer;
use Enqueue\Redis\RedisContext;
@@ -21,11 +22,6 @@ public function testShouldImplementConsumerInterface()
$this->assertClassImplements(Consumer::class, RedisConsumer::class);
}
- public function testCouldBeConstructedWithContextAndDestinationAndPreFetchCountAsArguments()
- {
- new RedisConsumer($this->createContextMock(), new RedisDestination('aQueue'));
- }
-
public function testShouldReturnDestinationSetInConstructorOnGetQueue()
{
$destination = new RedisDestination('aQueue');
@@ -35,41 +31,86 @@ public function testShouldReturnDestinationSetInConstructorOnGetQueue()
$this->assertSame($destination, $consumer->getQueue());
}
- public function testShouldDoNothingOnAcknowledge()
+ public function testShouldAcknowledgeMessage()
{
- $consumer = new RedisConsumer($this->createContextMock(), new RedisDestination('aQueue'));
+ $redisMock = $this->createRedisMock();
+ $redisMock
+ ->expects($this->once())
+ ->method('zrem')
+ ->with('aQueue:reserved', 'reserved-key')
+ ->willReturn(1)
+ ;
- $consumer->acknowledge(new RedisMessage());
- }
+ $contextMock = $this->createContextMock();
+ $contextMock
+ ->expects($this->once())
+ ->method('getRedis')
+ ->willReturn($redisMock)
+ ;
- public function testShouldDoNothingOnReject()
- {
- $consumer = new RedisConsumer($this->createContextMock(), new RedisDestination('aQueue'));
+ $message = new RedisMessage();
+ $message->setReservedKey('reserved-key');
+
+ $consumer = new RedisConsumer($contextMock, new RedisDestination('aQueue'));
- $consumer->reject(new RedisMessage());
+ $consumer->acknowledge($message);
}
- public function testShouldSendSameMessageToDestinationOnReQueue()
+ public function testShouldRejectMessage()
{
+ $redisMock = $this->createRedisMock();
+ $redisMock
+ ->expects($this->once())
+ ->method('zrem')
+ ->with('aQueue:reserved', 'reserved-key')
+ ->willReturn(1)
+ ;
+
+ $contextMock = $this->createContextMock();
+ $contextMock
+ ->expects($this->once())
+ ->method('getRedis')
+ ->willReturn($redisMock)
+ ;
+
$message = new RedisMessage();
+ $message->setReservedKey('reserved-key');
- $destination = new RedisDestination('aQueue');
+ $consumer = new RedisConsumer($contextMock, new RedisDestination('aQueue'));
+
+ $consumer->reject($message);
+ }
- $producerMock = $this->createProducerMock();
- $producerMock
+ public function testShouldSendSameMessageToDestinationOnReQueue()
+ {
+ $redisMock = $this->createRedisMock();
+ $redisMock
->expects($this->once())
- ->method('send')
- ->with($this->identicalTo($destination), $this->identicalTo($message))
+ ->method('lpush')
+ ->with('aQueue', '{"body":"text","properties":[],"headers":{"attempts":0}}')
+ ->willReturn(1)
;
+ $serializer = new JsonSerializer();
+
$contextMock = $this->createContextMock();
$contextMock
- ->expects($this->once())
- ->method('createProducer')
- ->willReturn($producerMock)
+ ->expects($this->any())
+ ->method('getRedis')
+ ->willReturn($redisMock)
+ ;
+ $contextMock
+ ->expects($this->any())
+ ->method('getSerializer')
+ ->willReturn($serializer)
;
- $consumer = new RedisConsumer($contextMock, $destination);
+ $message = new RedisMessage();
+ $message->setBody('text');
+ $message->setHeader('attempts', 0);
+ $message->setReservedKey($serializer->toString($message));
+
+ $consumer = new RedisConsumer($contextMock, new RedisDestination('aQueue'));
$consumer->reject($message, true);
}
@@ -88,7 +129,7 @@ public function testShouldCallRedisBRPopAndReturnNullIfNothingInQueueOnReceive()
$contextMock = $this->createContextMock();
$contextMock
- ->expects($this->once())
+ ->expects($this->any())
->method('getRedis')
->willReturn($redisMock)
;
@@ -102,20 +143,27 @@ public function testShouldCallRedisBRPopAndReturnMessageIfOneInQueueOnReceive()
{
$destination = new RedisDestination('aQueue');
+ $serializer = new JsonSerializer();
+
$redisMock = $this->createRedisMock();
$redisMock
->expects($this->once())
->method('brpop')
->with(['aQueue'], 2)
- ->willReturn(new RedisResult('aQueue', json_encode(new RedisMessage('aBody'))))
+ ->willReturn(new RedisResult('aQueue', $serializer->toString(new RedisMessage('aBody'))))
;
$contextMock = $this->createContextMock();
$contextMock
- ->expects($this->once())
+ ->expects($this->any())
->method('getRedis')
->willReturn($redisMock)
;
+ $contextMock
+ ->expects($this->any())
+ ->method('getSerializer')
+ ->willReturn($serializer)
+ ;
$consumer = new RedisConsumer($contextMock, $destination);
@@ -131,24 +179,26 @@ public function testShouldCallRedisBRPopSeveralTimesWithFiveSecondTimeoutIfZeroT
$expectedTimeout = 5;
+ $serializer = new JsonSerializer();
+
$redisMock = $this->createRedisMock();
$redisMock
- ->expects($this->at(0))
+ ->expects($this->at(2))
->method('brpop')
->with(['aQueue'], $expectedTimeout)
->willReturn(null)
;
$redisMock
- ->expects($this->at(1))
+ ->expects($this->at(5))
->method('brpop')
->with(['aQueue'], $expectedTimeout)
->willReturn(null)
;
$redisMock
- ->expects($this->at(2))
+ ->expects($this->at(8))
->method('brpop')
->with(['aQueue'], $expectedTimeout)
- ->willReturn(new RedisResult('aQueue', json_encode(new RedisMessage('aBody'))))
+ ->willReturn(new RedisResult('aQueue', $serializer->toString(new RedisMessage('aBody'))))
;
$contextMock = $this->createContextMock();
@@ -157,6 +207,11 @@ public function testShouldCallRedisBRPopSeveralTimesWithFiveSecondTimeoutIfZeroT
->method('getRedis')
->willReturn($redisMock)
;
+ $contextMock
+ ->expects($this->atLeastOnce())
+ ->method('getSerializer')
+ ->willReturn($serializer)
+ ;
$consumer = new RedisConsumer($contextMock, $destination);
@@ -170,6 +225,8 @@ public function testShouldCallRedisRPopAndReturnNullIfNothingInQueueOnReceiveNoW
{
$destination = new RedisDestination('aQueue');
+ $serializer = new JsonSerializer();
+
$redisMock = $this->createRedisMock();
$redisMock
->expects($this->once())
@@ -180,10 +237,15 @@ public function testShouldCallRedisRPopAndReturnNullIfNothingInQueueOnReceiveNoW
$contextMock = $this->createContextMock();
$contextMock
- ->expects($this->once())
+ ->expects($this->any())
->method('getRedis')
->willReturn($redisMock)
;
+ $contextMock
+ ->expects($this->any())
+ ->method('getSerializer')
+ ->willReturn($serializer)
+ ;
$consumer = new RedisConsumer($contextMock, $destination);
@@ -194,20 +256,27 @@ public function testShouldCallRedisRPopAndReturnMessageIfOneInQueueOnReceiveNoWa
{
$destination = new RedisDestination('aQueue');
+ $serializer = new JsonSerializer();
+
$redisMock = $this->createRedisMock();
$redisMock
->expects($this->once())
->method('rpop')
->with('aQueue')
- ->willReturn(new RedisResult('aQueue', json_encode(new RedisMessage('aBody'))))
+ ->willReturn(new RedisResult('aQueue', $serializer->toString(new RedisMessage('aBody'))))
;
$contextMock = $this->createContextMock();
$contextMock
- ->expects($this->once())
+ ->expects($this->atLeastOnce())
->method('getRedis')
->willReturn($redisMock)
;
+ $contextMock
+ ->expects($this->any())
+ ->method('getSerializer')
+ ->willReturn($serializer)
+ ;
$consumer = new RedisConsumer($contextMock, $destination);
@@ -218,7 +287,7 @@ public function testShouldCallRedisRPopAndReturnMessageIfOneInQueueOnReceiveNoWa
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Redis
+ * @return \PHPUnit\Framework\MockObject\MockObject|Redis
*/
private function createRedisMock()
{
@@ -226,7 +295,7 @@ private function createRedisMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|RedisProducer
+ * @return \PHPUnit\Framework\MockObject\MockObject|RedisProducer
*/
private function createProducerMock()
{
@@ -234,7 +303,7 @@ private function createProducerMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|RedisContext
+ * @return \PHPUnit\Framework\MockObject\MockObject|RedisContext
*/
private function createContextMock()
{
diff --git a/pkg/redis/Tests/RedisContextTest.php b/pkg/redis/Tests/RedisContextTest.php
index 94fb626f1..6395e954e 100644
--- a/pkg/redis/Tests/RedisContextTest.php
+++ b/pkg/redis/Tests/RedisContextTest.php
@@ -25,28 +25,16 @@ public function testShouldImplementContextInterface()
$this->assertClassImplements(Context::class, RedisContext::class);
}
- public function testCouldBeConstructedWithRedisAsFirstArgument()
- {
- new RedisContext($this->createRedisMock());
- }
-
- public function testCouldBeConstructedWithRedisFactoryAsFirstArgument()
- {
- new RedisContext(function () {
- return $this->createRedisMock();
- });
- }
-
public function testThrowIfNeitherRedisNorFactoryGiven()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The $redis argument must be either Enqueue\Redis\Redis or callable that returns Enqueue\Redis\Redis once called.');
- new RedisContext(new \stdClass());
+ new RedisContext(new \stdClass(), 300);
}
public function testShouldAllowCreateEmptyMessage()
{
- $context = new RedisContext($this->createRedisMock());
+ $context = new RedisContext($this->createRedisMock(), 300);
$message = $context->createMessage();
@@ -59,7 +47,7 @@ public function testShouldAllowCreateEmptyMessage()
public function testShouldAllowCreateCustomMessage()
{
- $context = new RedisContext($this->createRedisMock());
+ $context = new RedisContext($this->createRedisMock(), 300);
$message = $context->createMessage('theBody', ['aProp' => 'aPropVal'], ['aHeader' => 'aHeaderVal']);
@@ -72,7 +60,7 @@ public function testShouldAllowCreateCustomMessage()
public function testShouldCreateQueue()
{
- $context = new RedisContext($this->createRedisMock());
+ $context = new RedisContext($this->createRedisMock(), 300);
$queue = $context->createQueue('aQueue');
@@ -82,7 +70,7 @@ public function testShouldCreateQueue()
public function testShouldAllowCreateTopic()
{
- $context = new RedisContext($this->createRedisMock());
+ $context = new RedisContext($this->createRedisMock(), 300);
$topic = $context->createTopic('aTopic');
@@ -92,7 +80,7 @@ public function testShouldAllowCreateTopic()
public function testThrowNotImplementedOnCreateTmpQueueCall()
{
- $context = new RedisContext($this->createRedisMock());
+ $context = new RedisContext($this->createRedisMock(), 300);
$this->expectException(TemporaryQueueNotSupportedException::class);
@@ -101,7 +89,7 @@ public function testThrowNotImplementedOnCreateTmpQueueCall()
public function testShouldCreateProducer()
{
- $context = new RedisContext($this->createRedisMock());
+ $context = new RedisContext($this->createRedisMock(), 300);
$producer = $context->createProducer();
@@ -110,7 +98,7 @@ public function testShouldCreateProducer()
public function testShouldThrowIfNotRedisDestinationGivenOnCreateConsumer()
{
- $context = new RedisContext($this->createRedisMock());
+ $context = new RedisContext($this->createRedisMock(), 300);
$this->expectException(InvalidDestinationException::class);
$this->expectExceptionMessage('The destination must be an instance of Enqueue\Redis\RedisDestination but got Enqueue\Null\NullQueue.');
@@ -121,7 +109,7 @@ public function testShouldThrowIfNotRedisDestinationGivenOnCreateConsumer()
public function testShouldCreateConsumer()
{
- $context = new RedisContext($this->createRedisMock());
+ $context = new RedisContext($this->createRedisMock(), 300);
$queue = $context->createQueue('aQueue');
@@ -138,7 +126,7 @@ public function testShouldCallRedisDisconnectOnClose()
->method('disconnect')
;
- $context = new RedisContext($redisMock);
+ $context = new RedisContext($redisMock, 300);
$context->close();
}
@@ -151,7 +139,7 @@ public function testThrowIfNotRedisDestinationGivenOnDeleteQueue()
->method('del')
;
- $context = new RedisContext($redisMock);
+ $context = new RedisContext($redisMock, 300);
$this->expectException(InvalidDestinationException::class);
$context->deleteQueue(new NullQueue('aQueue'));
@@ -161,12 +149,22 @@ public function testShouldAllowDeleteQueue()
{
$redisMock = $this->createRedisMock();
$redisMock
- ->expects($this->once())
+ ->expects($this->at(0))
->method('del')
->with('aQueueName')
;
+ $redisMock
+ ->expects($this->at(1))
+ ->method('del')
+ ->with('aQueueName:delayed')
+ ;
+ $redisMock
+ ->expects($this->at(2))
+ ->method('del')
+ ->with('aQueueName:reserved')
+ ;
- $context = new RedisContext($redisMock);
+ $context = new RedisContext($redisMock, 300);
$queue = $context->createQueue('aQueueName');
@@ -181,7 +179,7 @@ public function testThrowIfNotRedisDestinationGivenOnDeleteTopic()
->method('del')
;
- $context = new RedisContext($redisMock);
+ $context = new RedisContext($redisMock, 300);
$this->expectException(InvalidDestinationException::class);
$context->deleteTopic(new NullTopic('aTopic'));
@@ -191,12 +189,22 @@ public function testShouldAllowDeleteTopic()
{
$redisMock = $this->createRedisMock();
$redisMock
- ->expects($this->once())
+ ->expects($this->at(0))
->method('del')
->with('aTopicName')
;
+ $redisMock
+ ->expects($this->at(1))
+ ->method('del')
+ ->with('aTopicName:delayed')
+ ;
+ $redisMock
+ ->expects($this->at(2))
+ ->method('del')
+ ->with('aTopicName:reserved')
+ ;
- $context = new RedisContext($redisMock);
+ $context = new RedisContext($redisMock, 300);
$topic = $context->createTopic('aTopicName');
@@ -205,13 +213,13 @@ public function testShouldAllowDeleteTopic()
public function testShouldReturnExpectedSubscriptionConsumerInstance()
{
- $context = new RedisContext($this->createRedisMock());
+ $context = new RedisContext($this->createRedisMock(), 300);
$this->assertInstanceOf(RedisSubscriptionConsumer::class, $context->createSubscriptionConsumer());
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Redis
+ * @return \PHPUnit\Framework\MockObject\MockObject|Redis
*/
private function createRedisMock()
{
diff --git a/pkg/redis/Tests/RedisMessageTest.php b/pkg/redis/Tests/RedisMessageTest.php
index 2a81efa5a..5b1e42fe2 100644
--- a/pkg/redis/Tests/RedisMessageTest.php
+++ b/pkg/redis/Tests/RedisMessageTest.php
@@ -9,11 +9,6 @@ class RedisMessageTest extends \PHPUnit\Framework\TestCase
{
use ClassExtensionTrait;
- public function testShouldImplementJsonSerializableInterface()
- {
- $this->assertClassImplements(\JsonSerializable::class, RedisMessage::class);
- }
-
public function testCouldConstructMessageWithoutArguments()
{
$message = new RedisMessage();
@@ -63,34 +58,4 @@ public function testShouldSetReplyToAsHeader()
$this->assertSame(['reply_to' => 'theQueueName'], $message->getHeaders());
}
-
- public function testColdBeSerializedToJson()
- {
- $message = new RedisMessage('theBody', ['thePropFoo' => 'thePropFooVal'], ['theHeaderFoo' => 'theHeaderFooVal']);
-
- $this->assertEquals('{"body":"theBody","properties":{"thePropFoo":"thePropFooVal"},"headers":{"theHeaderFoo":"theHeaderFooVal"}}', json_encode($message));
- }
-
- public function testCouldBeUnserializedFromJson()
- {
- $message = new RedisMessage('theBody', ['thePropFoo' => 'thePropFooVal'], ['theHeaderFoo' => 'theHeaderFooVal']);
-
- $json = json_encode($message);
-
- //guard
- $this->assertNotEmpty($json);
-
- $unserializedMessage = RedisMessage::jsonUnserialize($json);
-
- $this->assertInstanceOf(RedisMessage::class, $unserializedMessage);
- $this->assertEquals($message, $unserializedMessage);
- }
-
- public function testThrowIfMalformedJsonGivenOnUnsterilizedFromJson()
- {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The malformed json given.');
-
- RedisMessage::jsonUnserialize('{]');
- }
}
diff --git a/pkg/redis/Tests/RedisProducerTest.php b/pkg/redis/Tests/RedisProducerTest.php
index 98934826c..40e03bae2 100644
--- a/pkg/redis/Tests/RedisProducerTest.php
+++ b/pkg/redis/Tests/RedisProducerTest.php
@@ -4,7 +4,9 @@
use Enqueue\Null\NullMessage;
use Enqueue\Null\NullQueue;
+use Enqueue\Redis\JsonSerializer;
use Enqueue\Redis\Redis;
+use Enqueue\Redis\RedisContext;
use Enqueue\Redis\RedisDestination;
use Enqueue\Redis\RedisMessage;
use Enqueue\Redis\RedisProducer;
@@ -23,14 +25,9 @@ public function testShouldImplementProducerInterface()
$this->assertClassImplements(Producer::class, RedisProducer::class);
}
- public function testCouldBeConstructedWithRedisAsFirstArgument()
- {
- new RedisProducer($this->createRedisMock());
- }
-
public function testThrowIfDestinationNotRedisDestinationOnSend()
{
- $producer = new RedisProducer($this->createRedisMock());
+ $producer = new RedisProducer($this->createContextMock());
$this->expectException(InvalidDestinationException::class);
$this->expectExceptionMessage('The destination must be an instance of Enqueue\Redis\RedisDestination but got Enqueue\Null\NullQueue.');
@@ -39,7 +36,7 @@ public function testThrowIfDestinationNotRedisDestinationOnSend()
public function testThrowIfMessageNotRedisMessageOnSend()
{
- $producer = new RedisProducer($this->createRedisMock());
+ $producer = new RedisProducer($this->createContextMock());
$this->expectException(InvalidMessageException::class);
$this->expectExceptionMessage('The message must be an instance of Enqueue\Redis\RedisMessage but it is Enqueue\Null\NullMessage.');
@@ -54,16 +51,87 @@ public function testShouldCallLPushOnSend()
$redisMock
->expects($this->once())
->method('lpush')
- ->with('aDestination', '{"body":"","properties":[],"headers":[]}')
+ ->willReturnCallback(function (string $key, string $value) {
+ $this->assertSame('aDestination', $key);
+
+ $message = json_decode($value, true);
+
+ $this->assertArrayHasKey('body', $message);
+ $this->assertArrayHasKey('properties', $message);
+ $this->assertArrayHasKey('headers', $message);
+ $this->assertNotEmpty($message['headers']['message_id']);
+ $this->assertSame(0, $message['headers']['attempts']);
+
+ return 1;
+ })
;
- $producer = new RedisProducer($redisMock);
+ $context = $this->createContextMock();
+ $context
+ ->expects($this->once())
+ ->method('getRedis')
+ ->willReturn($redisMock)
+ ;
+ $context
+ ->expects($this->once())
+ ->method('getSerializer')
+ ->willReturn(new JsonSerializer())
+ ;
+
+ $producer = new RedisProducer($context);
$producer->send($destination, new RedisMessage());
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Redis
+ * Tests if Redis::zadd is called with the expected 'score' (used as delivery timestamp).
+ *
+ * @depends testShouldCallLPushOnSend
+ */
+ public function testShouldCallZaddOnSendWithDeliveryDelay()
+ {
+ $destination = new RedisDestination('aDestination');
+
+ $redisMock = $this->createRedisMock();
+ $redisMock
+ ->expects($this->once())
+ ->method('zadd')
+ ->with(
+ 'aDestination:delayed',
+ $this->isJson(),
+ $this->equalTo(time() + 5)
+ )
+ ;
+
+ $context = $this->createContextMock();
+ $context
+ ->expects($this->once())
+ ->method('getRedis')
+ ->willReturn($redisMock)
+ ;
+ $context
+ ->expects($this->once())
+ ->method('getSerializer')
+ ->willReturn(new JsonSerializer())
+ ;
+
+ $message = new RedisMessage();
+ $message->setDeliveryDelay(5000); // 5 seconds in milliseconds
+
+ $producer = new RedisProducer($context);
+ $producer->send($destination, $message);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|RedisContext
+ */
+ private function createContextMock()
+ {
+ return $this->createMock(RedisContext::class);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|Redis
*/
private function createRedisMock()
{
diff --git a/pkg/redis/Tests/RedisSubscriptionConsumerTest.php b/pkg/redis/Tests/RedisSubscriptionConsumerTest.php
index 12c377500..8d00fcc14 100644
--- a/pkg/redis/Tests/RedisSubscriptionConsumerTest.php
+++ b/pkg/redis/Tests/RedisSubscriptionConsumerTest.php
@@ -5,6 +5,7 @@
use Enqueue\Redis\RedisConsumer;
use Enqueue\Redis\RedisContext;
use Enqueue\Redis\RedisSubscriptionConsumer;
+use Enqueue\Test\ReadAttributeTrait;
use Interop\Queue\Consumer;
use Interop\Queue\Queue;
use Interop\Queue\SubscriptionConsumer;
@@ -12,6 +13,8 @@
class RedisSubscriptionConsumerTest extends TestCase
{
+ use ReadAttributeTrait;
+
public function testShouldImplementSubscriptionConsumerInterface()
{
$rc = new \ReflectionClass(RedisSubscriptionConsumer::class);
@@ -19,11 +22,6 @@ public function testShouldImplementSubscriptionConsumerInterface()
$this->assertTrue($rc->implementsInterface(SubscriptionConsumer::class));
}
- public function testCouldBeConstructedWithRedisContextAsFirstArgument()
- {
- new RedisSubscriptionConsumer($this->createRedisContextMock());
- }
-
public function testShouldAddConsumerAndCallbackToSubscribersPropertyOnSubscribe()
{
$subscriptionConsumer = new RedisSubscriptionConsumer($this->createRedisContextMock());
@@ -60,6 +58,9 @@ public function testThrowsIfTrySubscribeAnotherConsumerToAlreadySubscribedQueue(
$subscriptionConsumer->subscribe($barConsumer, $barCallback);
}
+ /**
+ * @doesNotPerformAssertions
+ */
public function testShouldAllowSubscribeSameConsumerAndCallbackSecondTime()
{
$subscriptionConsumer = new RedisSubscriptionConsumer($this->createRedisContextMock());
@@ -142,7 +143,7 @@ public function testThrowsIfTryConsumeWithoutSubscribers()
}
/**
- * @return RedisContext|\PHPUnit_Framework_MockObject_MockObject
+ * @return RedisContext|\PHPUnit\Framework\MockObject\MockObject
*/
private function createRedisContextMock()
{
@@ -150,9 +151,9 @@ private function createRedisContextMock()
}
/**
- * @param null|mixed $queueName
+ * @param mixed|null $queueName
*
- * @return Consumer|\PHPUnit_Framework_MockObject_MockObject
+ * @return Consumer|\PHPUnit\Framework\MockObject\MockObject
*/
private function createConsumerStub($queueName = null)
{
diff --git a/pkg/redis/Tests/Spec/JsonSerializerTest.php b/pkg/redis/Tests/Spec/JsonSerializerTest.php
new file mode 100644
index 000000000..a15859d35
--- /dev/null
+++ b/pkg/redis/Tests/Spec/JsonSerializerTest.php
@@ -0,0 +1,71 @@
+assertClassImplements(Serializer::class, JsonSerializer::class);
+ }
+
+ public function testShouldConvertMessageToJsonString()
+ {
+ $serializer = new JsonSerializer();
+
+ $message = new RedisMessage('theBody', ['aProp' => 'aPropVal'], ['aHeader' => 'aHeaderVal']);
+
+ $json = $serializer->toString($message);
+
+ $this->assertSame('{"body":"theBody","properties":{"aProp":"aPropVal"},"headers":{"aHeader":"aHeaderVal"}}', $json);
+ }
+
+ public function testThrowIfFailedToEncodeMessageToJson()
+ {
+ $serializer = new JsonSerializer();
+
+ $resource = fopen(__FILE__, 'r');
+
+ // guard
+ $this->assertIsResource($resource);
+
+ $message = new RedisMessage('theBody', ['aProp' => $resource]);
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The malformed json given.');
+ $serializer->toString($message);
+ }
+
+ public function testShouldConvertJsonStringToMessage()
+ {
+ $serializer = new JsonSerializer();
+
+ $message = $serializer->toMessage('{"body":"theBody","properties":{"aProp":"aPropVal"},"headers":{"aHeader":"aHeaderVal"}}');
+
+ $this->assertInstanceOf(RedisMessage::class, $message);
+
+ $this->assertSame('theBody', $message->getBody());
+ $this->assertSame(['aProp' => 'aPropVal'], $message->getProperties());
+ $this->assertSame(['aHeader' => 'aHeaderVal'], $message->getHeaders());
+ }
+
+ public function testThrowIfFailedToDecodeJsonToMessage()
+ {
+ $serializer = new JsonSerializer();
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The malformed json given.');
+ $serializer->toMessage('{]');
+ }
+}
diff --git a/pkg/redis/Tests/Spec/RedisConnectionFactoryTest.php b/pkg/redis/Tests/Spec/RedisConnectionFactoryTest.php
index e086bccab..f15282f11 100644
--- a/pkg/redis/Tests/Spec/RedisConnectionFactoryTest.php
+++ b/pkg/redis/Tests/Spec/RedisConnectionFactoryTest.php
@@ -10,9 +10,6 @@
*/
class RedisConnectionFactoryTest extends ConnectionFactorySpec
{
- /**
- * {@inheritdoc}
- */
protected function createConnectionFactory()
{
return new RedisConnectionFactory();
diff --git a/pkg/redis/Tests/Spec/RedisContextTest.php b/pkg/redis/Tests/Spec/RedisContextTest.php
index 3377fb89b..4f48e24ae 100644
--- a/pkg/redis/Tests/Spec/RedisContextTest.php
+++ b/pkg/redis/Tests/Spec/RedisContextTest.php
@@ -13,9 +13,6 @@ class RedisContextTest extends ContextSpec
{
use RedisExtension;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildPhpRedisContext();
diff --git a/pkg/redis/Tests/Spec/RedisMessageTest.php b/pkg/redis/Tests/Spec/RedisMessageTest.php
index bb8af845d..b0cc828e9 100644
--- a/pkg/redis/Tests/Spec/RedisMessageTest.php
+++ b/pkg/redis/Tests/Spec/RedisMessageTest.php
@@ -10,9 +10,6 @@
*/
class RedisMessageTest extends MessageSpec
{
- /**
- * {@inheritdoc}
- */
protected function createMessage()
{
return new RedisMessage();
diff --git a/pkg/redis/Tests/Spec/RedisProducerTest.php b/pkg/redis/Tests/Spec/RedisProducerTest.php
index fa9fbfefb..3434820e9 100644
--- a/pkg/redis/Tests/Spec/RedisProducerTest.php
+++ b/pkg/redis/Tests/Spec/RedisProducerTest.php
@@ -13,9 +13,6 @@ class RedisProducerTest extends ProducerSpec
{
use RedisExtension;
- /**
- * {@inheritdoc}
- */
protected function createProducer()
{
return $this->buildPhpRedisContext()->createProducer();
diff --git a/pkg/redis/Tests/Spec/RedisQueueTest.php b/pkg/redis/Tests/Spec/RedisQueueTest.php
index ab7b9937b..a8cd3b442 100644
--- a/pkg/redis/Tests/Spec/RedisQueueTest.php
+++ b/pkg/redis/Tests/Spec/RedisQueueTest.php
@@ -10,9 +10,6 @@
*/
class RedisQueueTest extends QueueSpec
{
- /**
- * {@inheritdoc}
- */
protected function createQueue()
{
return new RedisDestination(self::EXPECTED_QUEUE_NAME);
diff --git a/pkg/redis/Tests/Spec/RedisRequeueMessageTest.php b/pkg/redis/Tests/Spec/RedisRequeueMessageTest.php
index c84bc84b5..69bd2c6ef 100644
--- a/pkg/redis/Tests/Spec/RedisRequeueMessageTest.php
+++ b/pkg/redis/Tests/Spec/RedisRequeueMessageTest.php
@@ -13,9 +13,6 @@ class RedisRequeueMessageTest extends RequeueMessageSpec
{
use RedisExtension;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildPhpRedisContext();
diff --git a/pkg/redis/Tests/Spec/RedisSendToAndReceiveFromQueueTest.php b/pkg/redis/Tests/Spec/RedisSendToAndReceiveFromQueueTest.php
index 5535d949a..7bb61ab5d 100644
--- a/pkg/redis/Tests/Spec/RedisSendToAndReceiveFromQueueTest.php
+++ b/pkg/redis/Tests/Spec/RedisSendToAndReceiveFromQueueTest.php
@@ -13,9 +13,6 @@ class RedisSendToAndReceiveFromQueueTest extends SendToAndReceiveFromQueueSpec
{
use RedisExtension;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildPhpRedisContext();
diff --git a/pkg/redis/Tests/Spec/RedisSendToAndReceiveFromTopicTest.php b/pkg/redis/Tests/Spec/RedisSendToAndReceiveFromTopicTest.php
index 2967ba977..37545f032 100644
--- a/pkg/redis/Tests/Spec/RedisSendToAndReceiveFromTopicTest.php
+++ b/pkg/redis/Tests/Spec/RedisSendToAndReceiveFromTopicTest.php
@@ -13,9 +13,6 @@ class RedisSendToAndReceiveFromTopicTest extends SendToAndReceiveFromTopicSpec
{
use RedisExtension;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildPhpRedisContext();
diff --git a/pkg/redis/Tests/Spec/RedisSendToAndReceiveNoWaitFromQueueTest.php b/pkg/redis/Tests/Spec/RedisSendToAndReceiveNoWaitFromQueueTest.php
index e03139f7e..01aea7ff1 100644
--- a/pkg/redis/Tests/Spec/RedisSendToAndReceiveNoWaitFromQueueTest.php
+++ b/pkg/redis/Tests/Spec/RedisSendToAndReceiveNoWaitFromQueueTest.php
@@ -13,9 +13,6 @@ class RedisSendToAndReceiveNoWaitFromQueueTest extends SendToAndReceiveNoWaitFro
{
use RedisExtension;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildPhpRedisContext();
diff --git a/pkg/redis/Tests/Spec/RedisSendToAndReceiveNoWaitFromTopicTest.php b/pkg/redis/Tests/Spec/RedisSendToAndReceiveNoWaitFromTopicTest.php
index fe103234b..2c8fbac7a 100644
--- a/pkg/redis/Tests/Spec/RedisSendToAndReceiveNoWaitFromTopicTest.php
+++ b/pkg/redis/Tests/Spec/RedisSendToAndReceiveNoWaitFromTopicTest.php
@@ -13,9 +13,6 @@ class RedisSendToAndReceiveNoWaitFromTopicTest extends SendToAndReceiveNoWaitFro
{
use RedisExtension;
- /**
- * {@inheritdoc}
- */
protected function createContext()
{
return $this->buildPhpRedisContext();
diff --git a/pkg/redis/Tests/Spec/RedisSubscriptionConsumerConsumeFromAllSubscribedQueuesTest.php b/pkg/redis/Tests/Spec/RedisSubscriptionConsumerConsumeFromAllSubscribedQueuesTest.php
index 21d514fa5..78d33045f 100644
--- a/pkg/redis/Tests/Spec/RedisSubscriptionConsumerConsumeFromAllSubscribedQueuesTest.php
+++ b/pkg/redis/Tests/Spec/RedisSubscriptionConsumerConsumeFromAllSubscribedQueuesTest.php
@@ -18,8 +18,6 @@ class RedisSubscriptionConsumerConsumeFromAllSubscribedQueuesTest extends Subscr
/**
* @return RedisContext
- *
- * {@inheritdoc}
*/
protected function createContext()
{
@@ -28,14 +26,12 @@ protected function createContext()
/**
* @param RedisContext $context
- *
- * {@inheritdoc}
*/
protected function createQueue(Context $context, $queueName)
{
/** @var RedisDestination $queue */
$queue = parent::createQueue($context, $queueName);
- $context->getRedis()->del($queueName);
+ $context->deleteQueue($queue);
return $queue;
}
diff --git a/pkg/redis/Tests/Spec/RedisSubscriptionConsumerConsumeUntilUnsubscribedTest.php b/pkg/redis/Tests/Spec/RedisSubscriptionConsumerConsumeUntilUnsubscribedTest.php
index 9524e5b6f..84872093b 100644
--- a/pkg/redis/Tests/Spec/RedisSubscriptionConsumerConsumeUntilUnsubscribedTest.php
+++ b/pkg/redis/Tests/Spec/RedisSubscriptionConsumerConsumeUntilUnsubscribedTest.php
@@ -18,8 +18,6 @@ class RedisSubscriptionConsumerConsumeUntilUnsubscribedTest extends Subscription
/**
* @return RedisContext
- *
- * {@inheritdoc}
*/
protected function createContext()
{
@@ -28,14 +26,12 @@ protected function createContext()
/**
* @param RedisContext $context
- *
- * {@inheritdoc}
*/
protected function createQueue(Context $context, $queueName)
{
/** @var RedisDestination $queue */
$queue = parent::createQueue($context, $queueName);
- $context->getRedis()->del($queueName);
+ $context->purgeQueue($queue);
return $queue;
}
diff --git a/pkg/redis/Tests/Spec/RedisSubscriptionConsumerStopOnFalseTest.php b/pkg/redis/Tests/Spec/RedisSubscriptionConsumerStopOnFalseTest.php
index 5a033a872..490d58eab 100644
--- a/pkg/redis/Tests/Spec/RedisSubscriptionConsumerStopOnFalseTest.php
+++ b/pkg/redis/Tests/Spec/RedisSubscriptionConsumerStopOnFalseTest.php
@@ -18,8 +18,6 @@ class RedisSubscriptionConsumerStopOnFalseTest extends SubscriptionConsumerStopO
/**
* @return RedisContext
- *
- * {@inheritdoc}
*/
protected function createContext()
{
@@ -28,8 +26,6 @@ protected function createContext()
/**
* @param RedisContext $context
- *
- * {@inheritdoc}
*/
protected function createQueue(Context $context, $queueName)
{
diff --git a/pkg/redis/Tests/Spec/RedisTopicTest.php b/pkg/redis/Tests/Spec/RedisTopicTest.php
index 52001aa66..da94ffa1b 100644
--- a/pkg/redis/Tests/Spec/RedisTopicTest.php
+++ b/pkg/redis/Tests/Spec/RedisTopicTest.php
@@ -10,9 +10,6 @@
*/
class RedisTopicTest extends TopicSpec
{
- /**
- * {@inheritdoc}
- */
protected function createTopic()
{
return new RedisDestination(self::EXPECTED_TOPIC_NAME);
diff --git a/pkg/redis/composer.json b/pkg/redis/composer.json
index 878bc9cd5..c48323201 100644
--- a/pkg/redis/composer.json
+++ b/pkg/redis/composer.json
@@ -6,17 +6,17 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "queue-interop/queue-interop": "0.7.x-dev",
- "enqueue/dsn": "0.9.x-dev",
- "predis/predis": "^1.1"
+ "php": "^8.1",
+ "queue-interop/queue-interop": "^0.8",
+ "enqueue/dsn": "^0.10",
+ "ramsey/uuid": "^3.5|^4"
},
"require-dev": {
- "phpunit/phpunit": "~5.4.0",
+ "phpunit/phpunit": "^9.5",
"predis/predis": "^1.1",
- "enqueue/test": "0.9.x-dev",
- "enqueue/null": "0.9.x-dev",
- "queue-interop/queue-spec": "0.6.x-dev"
+ "enqueue/test": "0.10.x-dev",
+ "enqueue/null": "0.10.x-dev",
+ "queue-interop/queue-spec": "^0.6.2"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -37,7 +37,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/redis/phpunit.xml.dist b/pkg/redis/phpunit.xml.dist
index 9c4467b56..22691000e 100644
--- a/pkg/redis/phpunit.xml.dist
+++ b/pkg/redis/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/simple-client/.gitattributes b/pkg/simple-client/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/simple-client/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/simple-client/.github/workflows/ci.yml b/pkg/simple-client/.github/workflows/ci.yml
new file mode 100644
index 000000000..6bf7ab71b
--- /dev/null
+++ b/pkg/simple-client/.github/workflows/ci.yml
@@ -0,0 +1,31 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - run: php Tests/fix_composer_json.php
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/simple-client/.travis.yml b/pkg/simple-client/.travis.yml
deleted file mode 100644
index 408d8b7f9..000000000
--- a/pkg/simple-client/.travis.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-sudo: false
-
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
- - '7.2'
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - php Tests/fix_composer_json.php
- - composer self-update
- - composer install --prefer-source
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/simple-client/README.md b/pkg/simple-client/README.md
index 2368b31d7..1ec5e0424 100644
--- a/pkg/simple-client/README.md
+++ b/pkg/simple-client/README.md
@@ -1,26 +1,39 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Message Queue. Simple client
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/simple-client)
+[](https://github.com/php-enqueue/simple-client/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/simple-client)
[](https://packagist.org/packages/enqueue/simple-client)
-
-The simple client takes Enqueue client classes and Symfony components and combines it to easy to use facade called `SimpleCLient`.
+
+The simple client takes Enqueue client classes and Symfony components and combines it to easy to use facade called `SimpleClient`.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
diff --git a/pkg/simple-client/SimpleClient.php b/pkg/simple-client/SimpleClient.php
index de5922df7..bbfd8b91b 100644
--- a/pkg/simple-client/SimpleClient.php
+++ b/pkg/simple-client/SimpleClient.php
@@ -20,11 +20,14 @@
use Enqueue\ConnectionFactoryFactory;
use Enqueue\Consumption\CallbackProcessor;
use Enqueue\Consumption\ChainExtension as ConsumptionChainExtension;
+use Enqueue\Consumption\Extension\ReplyExtension;
+use Enqueue\Consumption\Extension\SignalExtension;
use Enqueue\Consumption\ExtensionInterface;
use Enqueue\Consumption\QueueConsumer;
use Enqueue\Consumption\QueueConsumerInterface;
use Enqueue\Rpc\Promise;
use Enqueue\Rpc\RpcFactory;
+use Enqueue\Symfony\Client\DependencyInjection\ClientFactory;
use Enqueue\Symfony\DependencyInjection\TransportFactory;
use Interop\Queue\Processor;
use Psr\Log\LoggerInterface;
@@ -98,31 +101,39 @@ final class SimpleClient
* 'transport' => 'null:',
* 'client' => [
* 'prefix' => 'enqueue',
+ * 'separator' => '.',
* 'app_name' => 'app',
* 'router_topic' => 'router',
* 'router_queue' => 'default',
- * 'default_processor_queue' => 'default',
+ * 'default_queue' => 'default',
* 'redelivered_delay_time' => 0
* ],
* 'extensions' => [
* 'signal_extension' => true,
+ * 'reply_extension' => true,
* ]
* ]
*
- *
* @param string|array $config
*/
- public function __construct($config, LoggerInterface $logger = null)
+ public function __construct($config, ?LoggerInterface $logger = null)
{
- $this->build(['enqueue' => $config]);
+ if (is_string($config)) {
+ $config = [
+ 'transport' => $config,
+ 'client' => true,
+ ];
+ }
$this->logger = $logger ?: new NullLogger();
+
+ $this->build(['enqueue' => $config]);
}
/**
* @param callable|Processor $processor
*/
- public function bindTopic(string $topic, $processor, string $processorName = null): void
+ public function bindTopic(string $topic, $processor, ?string $processorName = null): void
{
if (is_callable($processor)) {
$processor = new CallbackProcessor($processor);
@@ -132,7 +143,7 @@ public function bindTopic(string $topic, $processor, string $processorName = nul
throw new \LogicException('The processor must be either callable or instance of Processor');
}
- $processorName = $processorName ?: uniqid(get_class($processor));
+ $processorName = $processorName ?: uniqid($processor::class);
$this->driver->getRouteCollection()->add(new Route($topic, Route::TOPIC, $processorName));
$this->processorRegistry->add($processorName, $processor);
@@ -141,7 +152,7 @@ public function bindTopic(string $topic, $processor, string $processorName = nul
/**
* @param callable|Processor $processor
*/
- public function bindCommand(string $command, $processor, string $processorName = null): void
+ public function bindCommand(string $command, $processor, ?string $processorName = null): void
{
if (is_callable($processor)) {
$processor = new CallbackProcessor($processor);
@@ -151,7 +162,7 @@ public function bindCommand(string $command, $processor, string $processorName =
throw new \LogicException('The processor must be either callable or instance of Processor');
}
- $processorName = $processorName ?: uniqid(get_class($processor));
+ $processorName = $processorName ?: uniqid($processor::class);
$this->driver->getRouteCollection()->add(new Route($command, Route::COMMAND, $processorName));
$this->processorRegistry->add($processorName, $processor);
@@ -173,7 +184,7 @@ public function sendEvent(string $topic, $message): void
$this->producer->sendEvent($topic, $message);
}
- public function consume(ExtensionInterface $runtimeExtension = null): void
+ public function consume(?ExtensionInterface $runtimeExtension = null): void
{
$this->setupBroker();
@@ -214,6 +225,11 @@ public function getProducer(bool $setupBroker = false): ProducerInterface
return $this->producer;
}
+ public function getDelegateProcessor(): DelegateProcessor
+ {
+ return $this->delegateProcessor;
+ }
+
public function setupBroker(): void
{
$this->getDriver()->setupBroker();
@@ -241,20 +257,23 @@ public function build(array $configs): void
$config = new Config(
$simpleClientConfig['client']['prefix'],
+ $simpleClientConfig['client']['separator'],
$simpleClientConfig['client']['app_name'],
$simpleClientConfig['client']['router_topic'],
$simpleClientConfig['client']['router_queue'],
- $simpleClientConfig['client']['default_processor_queue'],
+ $simpleClientConfig['client']['default_queue'],
'enqueue.client.router_processor',
- $simpleClientConfig['transport']
+ $simpleClientConfig['transport'],
+ []
);
+
$routeCollection = new RouteCollection([]);
- $driverFactory = new DriverFactory($config, $routeCollection);
+ $driverFactory = new DriverFactory();
$driver = $driverFactory->create(
$connection,
- $simpleClientConfig['transport']['dsn'],
- $simpleClientConfig['transport']
+ $config,
+ $routeCollection
);
$rpcFactory = new RpcFactory($driver->getContext());
@@ -271,6 +290,14 @@ public function build(array $configs): void
$consumptionExtensions[] = new DelayRedeliveredMessageExtension($driver, $simpleClientConfig['client']['redelivered_delay_time']);
}
+ if ($simpleClientConfig['extensions']['signal_extension']) {
+ $consumptionExtensions[] = new SignalExtension();
+ }
+
+ if ($simpleClientConfig['extensions']['reply_extension']) {
+ $consumptionExtensions[] = new ReplyExtension();
+ }
+
$consumptionExtensions[] = new SetRouterPropertiesExtension($driver);
$consumptionExtensions[] = new LogExtension();
@@ -290,8 +317,13 @@ public function build(array $configs): void
private function createConfiguration(): NodeInterface
{
- $tb = new TreeBuilder();
- $rootNode = $tb->root('enqueue');
+ if (method_exists(TreeBuilder::class, 'getRootNode')) {
+ $tb = new TreeBuilder('enqueue');
+ $rootNode = $tb->getRootNode();
+ } else {
+ $tb = new TreeBuilder();
+ $rootNode = $tb->root('enqueue');
+ }
$rootNode
->beforeNormalization()
@@ -299,24 +331,17 @@ private function createConfiguration(): NodeInterface
return ['transport' => ['dsn' => 'null:']];
});
- $transportNode = $rootNode->children()->arrayNode('transport');
- (new TransportFactory('default'))->addTransportConfiguration($transportNode);
+ $rootNode
+ ->append(TransportFactory::getConfiguration())
+ ->append(TransportFactory::getQueueConsumerConfiguration())
+ ->append(ClientFactory::getConfiguration(false))
+ ;
$rootNode->children()
- ->arrayNode('client')
- ->addDefaultsIfNotSet()
- ->children()
- ->scalarNode('prefix')->defaultValue('enqueue')->end()
- ->scalarNode('app_name')->defaultValue('app')->end()
- ->scalarNode('router_topic')->defaultValue('default')->cannotBeEmpty()->end()
- ->scalarNode('router_queue')->defaultValue('default')->cannotBeEmpty()->end()
- ->scalarNode('default_processor_queue')->defaultValue('default')->cannotBeEmpty()->end()
- ->integerNode('redelivered_delay_time')->min(0)->defaultValue(0)->end()
- ->end()
- ->end()
- ->arrayNode('extensions')->addDefaultsIfNotSet()->children()
+ ->arrayNode('extensions')->addDefaultsIfNotSet()->children()
->booleanNode('signal_extension')->defaultValue(function_exists('pcntl_signal_dispatch'))->end()
- ->end()->end()
+ ->booleanNode('reply_extension')->defaultTrue()->end()
+ ->end()
;
return $tb->buildTree();
diff --git a/pkg/simple-client/Tests/Functional/SimpleClientTest.php b/pkg/simple-client/Tests/Functional/SimpleClientTest.php
index 63699c23b..ce75457af 100644
--- a/pkg/simple-client/Tests/Functional/SimpleClientTest.php
+++ b/pkg/simple-client/Tests/Functional/SimpleClientTest.php
@@ -56,12 +56,37 @@ public function transportConfigDataProvider()
], '+1sec'];
}
+ public function testShouldWorkWithStringDsnConstructorArgument()
+ {
+ $actualMessage = null;
+
+ $client = new SimpleClient(getenv('AMQP_DSN'));
+
+ $client->bindTopic('foo_topic', function (Message $message) use (&$actualMessage) {
+ $actualMessage = $message;
+
+ return Result::ACK;
+ });
+
+ $client->setupBroker();
+ $this->purgeQueue($client);
+
+ $client->sendEvent('foo_topic', 'Hello there!');
+
+ $client->getQueueConsumer()->setReceiveTimeout(200);
+ $client->consume(new ChainExtension([
+ new LimitConsumptionTimeExtension(new \DateTime('+1sec')),
+ new LimitConsumedMessagesExtension(2),
+ ]));
+
+ $this->assertInstanceOf(Message::class, $actualMessage);
+ $this->assertSame('Hello there!', $actualMessage->getBody());
+ }
+
/**
* @dataProvider transportConfigDataProvider
- *
- * @param mixed $config
*/
- public function testSendEventWithOneSubscriber(array $config, string $timeLimit)
+ public function testSendEventWithOneSubscriber($config, string $timeLimit)
{
$actualMessage = null;
@@ -70,7 +95,7 @@ public function testSendEventWithOneSubscriber(array $config, string $timeLimit)
'app_name' => 'simple_client',
'router_topic' => 'test',
'router_queue' => 'test',
- 'default_processor_queue' => 'test',
+ 'default_queue' => 'test',
];
$client = new SimpleClient($config);
@@ -98,10 +123,8 @@ public function testSendEventWithOneSubscriber(array $config, string $timeLimit)
/**
* @dataProvider transportConfigDataProvider
- *
- * @param mixed $config
*/
- public function testSendEventWithTwoSubscriber(array $config, string $timeLimit)
+ public function testSendEventWithTwoSubscriber($config, string $timeLimit)
{
$received = 0;
@@ -110,7 +133,7 @@ public function testSendEventWithTwoSubscriber(array $config, string $timeLimit)
'app_name' => 'simple_client',
'router_topic' => 'test',
'router_queue' => 'test',
- 'default_processor_queue' => 'test',
+ 'default_queue' => 'test',
];
$client = new SimpleClient($config);
@@ -141,10 +164,8 @@ public function testSendEventWithTwoSubscriber(array $config, string $timeLimit)
/**
* @dataProvider transportConfigDataProvider
- *
- * @param mixed $config
*/
- public function testSendCommand(array $config, string $timeLimit)
+ public function testSendCommand($config, string $timeLimit)
{
$received = 0;
@@ -153,7 +174,7 @@ public function testSendCommand(array $config, string $timeLimit)
'app_name' => 'simple_client',
'router_topic' => 'test',
'router_queue' => 'test',
- 'default_processor_queue' => 'test',
+ 'default_queue' => 'test',
];
$client = new SimpleClient($config);
diff --git a/pkg/simple-client/Tests/fix_composer_json.php b/pkg/simple-client/Tests/fix_composer_json.php
index fc430e276..01f73c95e 100644
--- a/pkg/simple-client/Tests/fix_composer_json.php
+++ b/pkg/simple-client/Tests/fix_composer_json.php
@@ -4,6 +4,6 @@
$composerJson = json_decode(file_get_contents(__DIR__.'/../composer.json'), true);
-$composerJson['config']['platform']['ext-amqp'] = '1.7';
+$composerJson['config']['platform']['ext-amqp'] = '1.9.3';
-file_put_contents(__DIR__.'/../composer.json', json_encode($composerJson, JSON_PRETTY_PRINT));
+file_put_contents(__DIR__.'/../composer.json', json_encode($composerJson, \JSON_PRETTY_PRINT));
diff --git a/pkg/simple-client/composer.json b/pkg/simple-client/composer.json
index 4f6c07a55..03bda03b4 100644
--- a/pkg/simple-client/composer.json
+++ b/pkg/simple-client/composer.json
@@ -6,18 +6,19 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "enqueue/enqueue": "0.9.x-dev",
- "queue-interop/amqp-interop": "0.8.x-dev",
- "queue-interop/queue-interop": "0.7.x-dev",
- "symfony/config": "^3.4|^4"
+ "php": "^8.1",
+ "enqueue/enqueue": "^0.10",
+ "queue-interop/amqp-interop": "^0.8.2",
+ "queue-interop/queue-interop": "^0.8",
+ "symfony/config": "^6.0|^7.0"
},
"require-dev": {
- "phpunit/phpunit": "~5.5",
- "enqueue/test": "0.9.x-dev",
- "enqueue/amqp-ext": "0.9.x-dev",
- "enqueue/fs": "0.9.x-dev",
- "enqueue/null": "0.9.x-dev"
+ "phpunit/phpunit": "^9.5",
+ "enqueue/test": "0.10.x-dev",
+ "enqueue/amqp-ext": "0.10.x-dev",
+ "enqueue/fs": "0.10.x-dev",
+ "enqueue/null": "0.10.x-dev",
+ "symfony/yaml": "^5.4|^6.0"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -35,7 +36,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/simple-client/phpunit.xml.dist b/pkg/simple-client/phpunit.xml.dist
index e86476dec..81d59cfaf 100644
--- a/pkg/simple-client/phpunit.xml.dist
+++ b/pkg/simple-client/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/sns/.gitattributes b/pkg/sns/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/sns/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/sns/.github/workflows/ci.yml b/pkg/sns/.github/workflows/ci.yml
new file mode 100644
index 000000000..c91cb39ab
--- /dev/null
+++ b/pkg/sns/.github/workflows/ci.yml
@@ -0,0 +1,29 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/sns/.gitignore b/pkg/sns/.gitignore
new file mode 100644
index 000000000..a770439e5
--- /dev/null
+++ b/pkg/sns/.gitignore
@@ -0,0 +1,6 @@
+*~
+/composer.lock
+/composer.phar
+/phpunit.xml
+/vendor/
+/.idea/
diff --git a/pkg/sns/LICENSE b/pkg/sns/LICENSE
new file mode 100644
index 000000000..20211e5fd
--- /dev/null
+++ b/pkg/sns/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+Copyright (c) 2018 Max Kotliar
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished
+to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/pkg/sns/README.md b/pkg/sns/README.md
new file mode 100644
index 000000000..bfc7a4012
--- /dev/null
+++ b/pkg/sns/README.md
@@ -0,0 +1,28 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
+# Amazon SNS Transport
+
+[](https://gitter.im/php-enqueue/Lobby)
+[](https://github.com/php-enqueue/sns/actions?query=workflow%3ACI)
+[](https://packagist.org/packages/enqueue/sns)
+[](https://packagist.org/packages/enqueue/sns)
+
+This is an implementation of Queue Interop specification. It allows you to send and consume message using [Amazon SNS](https://aws.amazon.com/sns/) service.
+
+## Resources
+
+* [Site](https://enqueue.forma-pro.com/)
+* [Documentation](https://php-enqueue.github.io/transport/sns/)
+* [Questions](https://gitter.im/php-enqueue/Lobby)
+* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
+
+## License
+
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/sns/SnsClient.php b/pkg/sns/SnsClient.php
new file mode 100644
index 000000000..7c4a81693
--- /dev/null
+++ b/pkg/sns/SnsClient.php
@@ -0,0 +1,145 @@
+inputClient = $inputClient;
+ }
+
+ public function createTopic(array $args): Result
+ {
+ return $this->callApi('createTopic', $args);
+ }
+
+ public function deleteTopic(string $topicArn): Result
+ {
+ return $this->callApi('DeleteTopic', [
+ 'TopicArn' => $topicArn,
+ ]);
+ }
+
+ public function publish(array $args): Result
+ {
+ return $this->callApi('publish', $args);
+ }
+
+ public function subscribe(array $args): Result
+ {
+ return $this->callApi('subscribe', $args);
+ }
+
+ public function unsubscribe(array $args): Result
+ {
+ return $this->callApi('unsubscribe', $args);
+ }
+
+ public function setSubscriptionAttributes(array $args): Result
+ {
+ return $this->callApi('setSubscriptionAttributes', $args);
+ }
+
+ public function listSubscriptionsByTopic(array $args): Result
+ {
+ return $this->callApi('ListSubscriptionsByTopic', $args);
+ }
+
+ public function getAWSClient(): AwsSnsClient
+ {
+ $this->resolveClient();
+
+ if ($this->singleClient) {
+ return $this->singleClient;
+ }
+
+ if ($this->multiClient) {
+ $mr = new \ReflectionMethod($this->multiClient, 'getClientFromPool');
+ $mr->setAccessible(true);
+ $singleClient = $mr->invoke($this->multiClient, $this->multiClient->getRegion());
+ $mr->setAccessible(false);
+
+ return $singleClient;
+ }
+
+ throw new \LogicException('The multi or single client must be set');
+ }
+
+ private function callApi(string $name, array $args): Result
+ {
+ $this->resolveClient();
+
+ if ($this->singleClient) {
+ if (false == empty($args['@region'])) {
+ throw new \LogicException('Cannot send message to another region because transport is configured with single aws client');
+ }
+
+ unset($args['@region']);
+
+ return call_user_func([$this->singleClient, $name], $args);
+ }
+
+ if ($this->multiClient) {
+ return call_user_func([$this->multiClient, $name], $args);
+ }
+
+ throw new \LogicException('The multi or single client must be set');
+ }
+
+ private function resolveClient(): void
+ {
+ if ($this->singleClient || $this->multiClient) {
+ return;
+ }
+
+ $client = $this->inputClient;
+ if ($client instanceof MultiRegionClient) {
+ $this->multiClient = $client;
+
+ return;
+ } elseif ($client instanceof AwsSnsClient) {
+ $this->singleClient = $client;
+
+ return;
+ } elseif (is_callable($client)) {
+ $client = call_user_func($client);
+ if ($client instanceof MultiRegionClient) {
+ $this->multiClient = $client;
+
+ return;
+ }
+ if ($client instanceof AwsSnsClient) {
+ $this->singleClient = $client;
+
+ return;
+ }
+ }
+
+ throw new \LogicException(sprintf('The input client must be an instance of "%s" or "%s" or a callable that returns one of those. Got "%s"', AwsSnsClient::class, MultiRegionClient::class, is_object($client) ? $client::class : gettype($client)));
+ }
+}
diff --git a/pkg/sns/SnsConnectionFactory.php b/pkg/sns/SnsConnectionFactory.php
new file mode 100644
index 000000000..8a815abad
--- /dev/null
+++ b/pkg/sns/SnsConnectionFactory.php
@@ -0,0 +1,159 @@
+ null, AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
+ * 'secret' => null, AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
+ * 'token' => null, AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
+ * 'region' => null, (string, required) Region to connect to. See http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of available regions.
+ * 'version' => '2012-11-05', (string, required) The version of the webservice to utilize
+ * 'lazy' => true, Enable lazy connection (boolean)
+ * 'endpoint' => null, (string, default=null) The full URI of the webservice. This is only required when connecting to a custom endpoint e.g. localstack
+ * 'topic_arns' => [], (array) The list of existing topic arns: key - topic name; value - arn
+ * ].
+ *
+ * or
+ *
+ * sns:
+ * sns::?key=aKey&secret=aSecret&token=aToken
+ *
+ * @param array|string|SnsClient|null $config
+ */
+ public function __construct($config = 'sns:')
+ {
+ if ($config instanceof AwsSnsClient) {
+ $this->client = new SnsClient($config);
+ $this->config = ['lazy' => false] + $this->defaultConfig();
+
+ return;
+ }
+
+ if (empty($config)) {
+ $config = [];
+ } elseif (\is_string($config)) {
+ $config = $this->parseDsn($config);
+ } elseif (\is_array($config)) {
+ if (\array_key_exists('dsn', $config)) {
+ $config = \array_replace_recursive($config, $this->parseDsn($config['dsn']));
+
+ unset($config['dsn']);
+ }
+ } else {
+ throw new \LogicException(\sprintf('The config must be either an array of options, a DSN string, null or instance of %s', AwsSnsClient::class));
+ }
+
+ $this->config = \array_replace($this->defaultConfig(), $config);
+ }
+
+ /**
+ * @return SnsContext
+ */
+ public function createContext(): Context
+ {
+ return new SnsContext($this->establishConnection(), $this->config);
+ }
+
+ private function establishConnection(): SnsClient
+ {
+ if ($this->client) {
+ return $this->client;
+ }
+
+ $config = [
+ 'version' => $this->config['version'],
+ 'region' => $this->config['region'],
+ ];
+
+ if (isset($this->config['endpoint'])) {
+ $config['endpoint'] = $this->config['endpoint'];
+ }
+
+ if (isset($this->config['profile'])) {
+ $config['profile'] = $this->config['profile'];
+ }
+
+ if ($this->config['key'] && $this->config['secret']) {
+ $config['credentials'] = [
+ 'key' => $this->config['key'],
+ 'secret' => $this->config['secret'],
+ ];
+
+ if ($this->config['token']) {
+ $config['credentials']['token'] = $this->config['token'];
+ }
+ }
+
+ if (isset($this->config['http'])) {
+ $config['http'] = $this->config['http'];
+ }
+
+ $establishConnection = function () use ($config) {
+ return (new Sdk(['Sns' => $config]))->createMultiRegionSns();
+ };
+
+ $this->client = $this->config['lazy'] ?
+ new SnsClient($establishConnection) :
+ new SnsClient($establishConnection())
+ ;
+
+ return $this->client;
+ }
+
+ private function parseDsn(string $dsn): array
+ {
+ $dsn = Dsn::parseFirst($dsn);
+
+ if ('sns' !== $dsn->getSchemeProtocol()) {
+ throw new \LogicException(\sprintf('The given scheme protocol "%s" is not supported. It must be "sns"', $dsn->getSchemeProtocol()));
+ }
+
+ return \array_filter(\array_replace($dsn->getQuery(), [
+ 'key' => $dsn->getString('key'),
+ 'secret' => $dsn->getString('secret'),
+ 'token' => $dsn->getString('token'),
+ 'region' => $dsn->getString('region'),
+ 'version' => $dsn->getString('version'),
+ 'lazy' => $dsn->getBool('lazy'),
+ 'endpoint' => $dsn->getString('endpoint'),
+ 'topic_arns' => $dsn->getArray('topic_arns', [])->toArray(),
+ 'http' => $dsn->getArray('http', [])->toArray(),
+ ]), function ($value) { return null !== $value; });
+ }
+
+ private function defaultConfig(): array
+ {
+ return [
+ 'key' => null,
+ 'secret' => null,
+ 'token' => null,
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'lazy' => true,
+ 'endpoint' => null,
+ 'topic_arns' => [],
+ 'http' => [],
+ ];
+ }
+}
diff --git a/pkg/sns/SnsContext.php b/pkg/sns/SnsContext.php
new file mode 100644
index 000000000..2e19164d9
--- /dev/null
+++ b/pkg/sns/SnsContext.php
@@ -0,0 +1,214 @@
+client = $client;
+ $this->config = $config;
+ $this->topicArns = $config['topic_arns'] ?? [];
+ }
+
+ /**
+ * @return SnsMessage
+ */
+ public function createMessage(string $body = '', array $properties = [], array $headers = []): Message
+ {
+ return new SnsMessage($body, $properties, $headers);
+ }
+
+ /**
+ * @return SnsDestination
+ */
+ public function createTopic(string $topicName): Topic
+ {
+ return new SnsDestination($topicName);
+ }
+
+ /**
+ * @return SnsDestination
+ */
+ public function createQueue(string $queueName): Queue
+ {
+ return new SnsDestination($queueName);
+ }
+
+ public function declareTopic(SnsDestination $destination): void
+ {
+ $result = $this->client->createTopic([
+ 'Attributes' => $destination->getAttributes(),
+ 'Name' => $destination->getQueueName(),
+ ]);
+
+ if (false == $result->hasKey('TopicArn')) {
+ throw new \RuntimeException(sprintf('Cannot create topic. topicName: "%s"', $destination->getTopicName()));
+ }
+
+ $this->topicArns[$destination->getTopicName()] = (string) $result->get('TopicArn');
+ }
+
+ public function setTopicArn(SnsDestination $destination, string $arn): void
+ {
+ $this->topicArns[$destination->getTopicName()] = $arn;
+ }
+
+ public function deleteTopic(SnsDestination $destination): void
+ {
+ $this->client->deleteTopic($this->getTopicArn($destination));
+
+ unset($this->topicArns[$destination->getTopicName()]);
+ }
+
+ public function subscribe(SnsSubscribe $subscribe): void
+ {
+ foreach ($this->getSubscriptions($subscribe->getTopic()) as $subscription) {
+ if ($subscription['Protocol'] === $subscribe->getProtocol()
+ && $subscription['Endpoint'] === $subscribe->getEndpoint()) {
+ return;
+ }
+ }
+
+ $this->client->subscribe([
+ 'Attributes' => $subscribe->getAttributes(),
+ 'Endpoint' => $subscribe->getEndpoint(),
+ 'Protocol' => $subscribe->getProtocol(),
+ 'ReturnSubscriptionArn' => $subscribe->isReturnSubscriptionArn(),
+ 'TopicArn' => $this->getTopicArn($subscribe->getTopic()),
+ ]);
+ }
+
+ public function unsubscibe(SnsUnsubscribe $unsubscribe): void
+ {
+ foreach ($this->getSubscriptions($unsubscribe->getTopic()) as $subscription) {
+ if ($subscription['Protocol'] != $unsubscribe->getProtocol()) {
+ continue;
+ }
+
+ if ($subscription['Endpoint'] != $unsubscribe->getEndpoint()) {
+ continue;
+ }
+
+ $this->client->unsubscribe([
+ 'SubscriptionArn' => $subscription['SubscriptionArn'],
+ ]);
+ }
+ }
+
+ public function getSubscriptions(SnsDestination $destination): array
+ {
+ $args = [
+ 'TopicArn' => $this->getTopicArn($destination),
+ ];
+
+ $subscriptions = [];
+ while (true) {
+ $result = $this->client->listSubscriptionsByTopic($args);
+
+ $subscriptions = array_merge($subscriptions, $result->get('Subscriptions'));
+
+ if (false == $result->hasKey('NextToken')) {
+ break;
+ }
+
+ $args['NextToken'] = $result->get('NextToken');
+ }
+
+ return $subscriptions;
+ }
+
+ public function setSubscriptionAttributes(SnsSubscribe $subscribe): void
+ {
+ foreach ($this->getSubscriptions($subscribe->getTopic()) as $subscription) {
+ $this->client->setSubscriptionAttributes(array_merge(
+ $subscribe->getAttributes(),
+ ['SubscriptionArn' => $subscription['SubscriptionArn']],
+ ));
+ }
+ }
+
+ public function getTopicArn(SnsDestination $destination): string
+ {
+ if (false == array_key_exists($destination->getTopicName(), $this->topicArns)) {
+ $this->declareTopic($destination);
+ }
+
+ return $this->topicArns[$destination->getTopicName()];
+ }
+
+ public function createTemporaryQueue(): Queue
+ {
+ throw TemporaryQueueNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ /**
+ * @return SnsProducer
+ */
+ public function createProducer(): Producer
+ {
+ return new SnsProducer($this);
+ }
+
+ /**
+ * @param SnsDestination $destination
+ */
+ public function createConsumer(Destination $destination): Consumer
+ {
+ throw new \LogicException('SNS transport does not support consumption. You should consider using SQS instead.');
+ }
+
+ public function close(): void
+ {
+ }
+
+ /**
+ * @param SnsDestination $queue
+ */
+ public function purgeQueue(Queue $queue): void
+ {
+ PurgeQueueNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function createSubscriptionConsumer(): SubscriptionConsumer
+ {
+ throw SubscriptionConsumerNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function getAwsSnsClient(): AwsSnsClient
+ {
+ return $this->client->getAWSClient();
+ }
+
+ public function getSnsClient(): SnsClient
+ {
+ return $this->client;
+ }
+}
diff --git a/pkg/sns/SnsDestination.php b/pkg/sns/SnsDestination.php
new file mode 100644
index 000000000..adcb08f43
--- /dev/null
+++ b/pkg/sns/SnsDestination.php
@@ -0,0 +1,119 @@
+name = $name;
+ $this->attributes = [];
+ }
+
+ public function getQueueName(): string
+ {
+ return $this->name;
+ }
+
+ public function getTopicName(): string
+ {
+ return $this->name;
+ }
+
+ /**
+ * The policy that defines who can access your topic. By default, only the topic owner can publish or subscribe to the topic.
+ */
+ public function setPolicy(?string $policy = null): void
+ {
+ $this->setAttribute('Policy', $policy);
+ }
+
+ public function getPolicy(): ?string
+ {
+ return $this->getAttribute('Policy');
+ }
+
+ /**
+ * The display name to use for a topic with SMS subscriptions.
+ */
+ public function setDisplayName(?string $displayName = null): void
+ {
+ $this->setAttribute('DisplayName', $displayName);
+ }
+
+ public function getDisplayName(): ?string
+ {
+ return $this->getAttribute('DisplayName');
+ }
+
+ /**
+ * The display name to use for a topic with SMS subscriptions.
+ */
+ public function setDeliveryPolicy(?int $deliveryPolicy = null): void
+ {
+ $this->setAttribute('DeliveryPolicy', $deliveryPolicy);
+ }
+
+ public function getDeliveryPolicy(): ?int
+ {
+ return $this->getAttribute('DeliveryPolicy');
+ }
+
+ /**
+ * Only FIFO.
+ *
+ * Designates a topic as FIFO. You can provide this attribute only during queue creation.
+ * You can't change it for an existing topic. When you set this attribute, you must provide aMessageGroupId
+ * explicitly.
+ * For more information, see https://docs.aws.amazon.com/sns/latest/dg/sns-fifo-topics.html
+ */
+ public function setFifoTopic(bool $enable): void
+ {
+ $value = $enable ? 'true' : null;
+
+ $this->setAttribute('FifoTopic', $value);
+ }
+
+ /**
+ * Only FIFO.
+ *
+ * Enables content-based deduplication.
+ * For more information, see: https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html
+ */
+ public function setContentBasedDeduplication(bool $enable): void
+ {
+ $value = $enable ? 'true' : null;
+
+ $this->setAttribute('ContentBasedDeduplication', $value);
+ }
+
+ public function getAttributes(): array
+ {
+ return $this->attributes;
+ }
+
+ private function getAttribute(string $name, $default = null)
+ {
+ return array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default;
+ }
+
+ private function setAttribute(string $name, $value): void
+ {
+ if (null == $value) {
+ unset($this->attributes[$name]);
+ } else {
+ $this->attributes[$name] = $value;
+ }
+ }
+}
diff --git a/pkg/sns/SnsMessage.php b/pkg/sns/SnsMessage.php
new file mode 100644
index 000000000..4122209e8
--- /dev/null
+++ b/pkg/sns/SnsMessage.php
@@ -0,0 +1,222 @@
+body = $body;
+ $this->properties = $properties;
+ $this->headers = $headers;
+ $this->messageAttributes = $messageAttributes;
+ $this->messageStructure = $messageStructure;
+ $this->phoneNumber = $phoneNumber;
+ $this->subject = $subject;
+ $this->targetArn = $targetArn;
+ $this->redelivered = false;
+ }
+
+ public function getSnsMessageId(): ?string
+ {
+ return $this->snsMessageId;
+ }
+
+ public function setSnsMessageId(?string $snsMessageId): void
+ {
+ $this->snsMessageId = $snsMessageId;
+ }
+
+ public function getMessageStructure(): ?string
+ {
+ return $this->messageStructure;
+ }
+
+ public function setMessageStructure(?string $messageStructure): void
+ {
+ $this->messageStructure = $messageStructure;
+ }
+
+ public function getPhoneNumber(): ?string
+ {
+ return $this->phoneNumber;
+ }
+
+ public function setPhoneNumber(?string $phoneNumber): void
+ {
+ $this->phoneNumber = $phoneNumber;
+ }
+
+ public function getSubject(): ?string
+ {
+ return $this->subject;
+ }
+
+ public function setSubject(?string $subject): void
+ {
+ $this->subject = $subject;
+ }
+
+ public function getMessageAttributes(): ?array
+ {
+ return $this->messageAttributes;
+ }
+
+ public function setMessageAttributes(?array $messageAttributes): void
+ {
+ $this->messageAttributes = $messageAttributes;
+ }
+
+ /**
+ * @param null $default
+ *
+ * @return array|null
+ */
+ public function getAttribute(string $name, $default = null)
+ {
+ return array_key_exists($name, $this->messageAttributes) ? $this->messageAttributes[$name] : $default;
+ }
+
+ /**
+ * Attribute array format:
+ * [
+ * 'BinaryValue' => ,
+ * 'DataType' => '', // REQUIRED
+ * 'StringValue' => '',
+ * ].
+ */
+ public function setAttribute(string $name, ?array $attribute): void
+ {
+ if (null === $attribute) {
+ unset($this->messageAttributes[$name]);
+ } else {
+ $this->messageAttributes[$name] = $attribute;
+ }
+ }
+
+ /**
+ * @param string $dataType String, String.Array, Number, or Binary
+ * @param string|resource|StreamInterface $value
+ */
+ public function addAttribute(string $name, string $dataType, $value): void
+ {
+ $valueKey = 'Binary' === $dataType ? 'BinaryValue' : 'StringValue';
+
+ $this->messageAttributes[$name] = [
+ 'DataType' => $dataType,
+ $valueKey => $value,
+ ];
+ }
+
+ public function getTargetArn(): ?string
+ {
+ return $this->targetArn;
+ }
+
+ public function setTargetArn(?string $targetArn): void
+ {
+ $this->targetArn = $targetArn;
+ }
+
+ /**
+ * Only FIFO.
+ *
+ * The tag that specifies that a message belongs to a specific message group. Messages that belong to the same
+ * message group are processed in a FIFO manner (however, messages in different message groups might be processed
+ * out of order).
+ * To interleave multiple ordered streams within a single queue, use MessageGroupId values (for example, session
+ * data for multiple users). In this scenario, multiple readers can process the queue, but the session data
+ * of each user is processed in a FIFO fashion.
+ * For more information, see: https://docs.aws.amazon.com/sns/latest/dg/fifo-message-grouping.html
+ */
+ public function setMessageGroupId(?string $id = null): void
+ {
+ $this->messageGroupId = $id;
+ }
+
+ public function getMessageGroupId(): ?string
+ {
+ return $this->messageGroupId;
+ }
+
+ /**
+ * Only FIFO.
+ *
+ * The token used for deduplication of sent messages. If a message with a particular MessageDeduplicationId is
+ * sent successfully, any messages sent with the same MessageDeduplicationId are accepted successfully but
+ * aren't delivered during the 5-minute deduplication interval.
+ * For more information, see https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html
+ */
+ public function setMessageDeduplicationId(?string $id = null): void
+ {
+ $this->messageDeduplicationId = $id;
+ }
+
+ public function getMessageDeduplicationId(): ?string
+ {
+ return $this->messageDeduplicationId;
+ }
+}
diff --git a/pkg/sns/SnsProducer.php b/pkg/sns/SnsProducer.php
new file mode 100644
index 000000000..ac7e38b5b
--- /dev/null
+++ b/pkg/sns/SnsProducer.php
@@ -0,0 +1,153 @@
+context = $context;
+ }
+
+ /**
+ * @param SnsDestination $destination
+ * @param SnsMessage $message
+ */
+ public function send(Destination $destination, Message $message): void
+ {
+ InvalidDestinationException::assertDestinationInstanceOf($destination, SnsDestination::class);
+ InvalidMessageException::assertMessageInstanceOf($message, SnsMessage::class);
+
+ $body = $message->getBody();
+ if (empty($body)) {
+ throw new InvalidMessageException('The message body must be a non-empty string.');
+ }
+
+ $topicArn = $this->context->getTopicArn($destination);
+
+ $arguments = [
+ 'Message' => $message->getBody(),
+ 'MessageAttributes' => [
+ 'Headers' => [
+ 'DataType' => 'String',
+ 'StringValue' => json_encode([$message->getHeaders(), $message->getProperties()]),
+ ],
+ ],
+ 'TopicArn' => $topicArn,
+ ];
+
+ if (null !== $message->getMessageAttributes()) {
+ $arguments['MessageAttributes'] = array_merge(
+ $arguments['MessageAttributes'],
+ $message->getMessageAttributes()
+ );
+ }
+
+ if (null !== ($structure = $message->getMessageStructure())) {
+ $arguments['MessageStructure'] = $structure;
+ }
+ if (null !== ($phone = $message->getPhoneNumber())) {
+ $arguments['PhoneNumber'] = $phone;
+ }
+ if (null !== ($subject = $message->getSubject())) {
+ $arguments['Subject'] = $subject;
+ }
+ if (null !== ($targetArn = $message->getTargetArn())) {
+ $arguments['TargetArn'] = $targetArn;
+ }
+
+ if ($messageGroupId = $message->getMessageGroupId()) {
+ $arguments['MessageGroupId'] = $messageGroupId;
+ }
+
+ if ($messageDeduplicationId = $message->getMessageDeduplicationId()) {
+ $arguments['MessageDeduplicationId'] = $messageDeduplicationId;
+ }
+
+ $result = $this->context->getSnsClient()->publish($arguments);
+
+ if (false == $result->hasKey('MessageId')) {
+ throw new \RuntimeException('Message was not sent');
+ }
+
+ $message->setSnsMessageId((string) $result->get('MessageId'));
+ }
+
+ /**
+ * @throws DeliveryDelayNotSupportedException
+ *
+ * @return SnsProducer
+ */
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
+ {
+ if (null === $deliveryDelay) {
+ return $this;
+ }
+
+ throw DeliveryDelayNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function getDeliveryDelay(): ?int
+ {
+ return $this->deliveryDelay;
+ }
+
+ /**
+ * @throws PriorityNotSupportedException
+ *
+ * @return SnsProducer
+ */
+ public function setPriority(?int $priority = null): Producer
+ {
+ if (null === $priority) {
+ return $this;
+ }
+
+ throw PriorityNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function getPriority(): ?int
+ {
+ return null;
+ }
+
+ /**
+ * @throws TimeToLiveNotSupportedException
+ *
+ * @return SnsProducer
+ */
+ public function setTimeToLive(?int $timeToLive = null): Producer
+ {
+ if (null === $timeToLive) {
+ return $this;
+ }
+
+ throw TimeToLiveNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function getTimeToLive(): ?int
+ {
+ return null;
+ }
+}
diff --git a/pkg/sns/SnsSubscribe.php b/pkg/sns/SnsSubscribe.php
new file mode 100644
index 000000000..52991d81f
--- /dev/null
+++ b/pkg/sns/SnsSubscribe.php
@@ -0,0 +1,68 @@
+topic = $topic;
+ $this->endpoint = $endpoint;
+ $this->protocol = $protocol;
+ $this->returnSubscriptionArn = $returnSubscriptionArn;
+ $this->attributes = $attributes;
+ }
+
+ public function getTopic(): SnsDestination
+ {
+ return $this->topic;
+ }
+
+ public function getEndpoint(): string
+ {
+ return $this->endpoint;
+ }
+
+ public function getProtocol(): string
+ {
+ return $this->protocol;
+ }
+
+ public function isReturnSubscriptionArn(): bool
+ {
+ return $this->returnSubscriptionArn;
+ }
+
+ public function getAttributes(): array
+ {
+ return $this->attributes;
+ }
+}
diff --git a/pkg/sns/SnsUnsubscribe.php b/pkg/sns/SnsUnsubscribe.php
new file mode 100644
index 000000000..ad6b93d45
--- /dev/null
+++ b/pkg/sns/SnsUnsubscribe.php
@@ -0,0 +1,48 @@
+topic = $topic;
+ $this->endpoint = $endpoint;
+ $this->protocol = $protocol;
+ }
+
+ public function getTopic(): SnsDestination
+ {
+ return $this->topic;
+ }
+
+ public function getEndpoint(): string
+ {
+ return $this->endpoint;
+ }
+
+ public function getProtocol(): string
+ {
+ return $this->protocol;
+ }
+}
diff --git a/pkg/sns/Tests/SnsClientTest.php b/pkg/sns/Tests/SnsClientTest.php
new file mode 100644
index 000000000..a029f4fd0
--- /dev/null
+++ b/pkg/sns/Tests/SnsClientTest.php
@@ -0,0 +1,227 @@
+ [
+ 'key' => '',
+ 'secret' => '',
+ 'region' => 'us-west-2',
+ 'version' => '2010-03-31',
+ 'endpoint' => 'http://localhost',
+ ]]))->createSns();
+
+ $client = new SnsClient($awsClient);
+
+ $this->assertSame($awsClient, $client->getAWSClient());
+ }
+
+ public function testShouldAllowGetAwsClientIfMultipleClientProvided()
+ {
+ $awsClient = (new Sdk(['Sns' => [
+ 'key' => '',
+ 'secret' => '',
+ 'region' => 'us-west-2',
+ 'version' => '2010-03-31',
+ 'endpoint' => 'http://localhost',
+ ]]))->createMultiRegionSns();
+
+ $client = new SnsClient($awsClient);
+
+ $this->assertInstanceOf(AwsSnsClient::class, $client->getAWSClient());
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ * @dataProvider provideApiCallsMultipleClient
+ */
+ public function testApiCall(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $awsClient = $this->getMockBuilder($awsClientClass)
+ ->disableOriginalConstructor()
+ ->setMethods([$method])
+ ->getMock();
+ $awsClient
+ ->expects($this->once())
+ ->method($method)
+ ->with($this->identicalTo($args))
+ ->willReturn(new Result($result));
+
+ $client = new SnsClient($awsClient);
+
+ $actualResult = $client->{$method}($args);
+
+ $this->assertInstanceOf(Result::class, $actualResult);
+ $this->assertSame($result, $actualResult->toArray());
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ * @dataProvider provideApiCallsMultipleClient
+ */
+ public function testLazyApiCall(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $awsClient = $this->getMockBuilder($awsClientClass)
+ ->disableOriginalConstructor()
+ ->setMethods([$method])
+ ->getMock();
+ $awsClient
+ ->expects($this->once())
+ ->method($method)
+ ->with($this->identicalTo($args))
+ ->willReturn(new Result($result));
+
+ $client = new SnsClient(function () use ($awsClient) {
+ return $awsClient;
+ });
+
+ $actualResult = $client->{$method}($args);
+
+ $this->assertInstanceOf(Result::class, $actualResult);
+ $this->assertSame($result, $actualResult->toArray());
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ * @dataProvider provideApiCallsMultipleClient
+ */
+ public function testThrowIfInvalidInputClientApiCall(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $client = new SnsClient(new \stdClass());
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The input client must be an instance of "Aws\Sns\SnsClient" or "Aws\MultiRegionClient" or a callable that returns one of those. Got "stdClass"');
+ $client->{$method}($args);
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ * @dataProvider provideApiCallsMultipleClient
+ */
+ public function testThrowIfInvalidLazyInputClientApiCall(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $client = new SnsClient(function () { return new \stdClass(); });
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The input client must be an instance of "Aws\Sns\SnsClient" or "Aws\MultiRegionClient" or a callable that returns one of those. Got "stdClass"');
+ $client->{$method}($args);
+ }
+
+ /**
+ * @dataProvider provideApiCallsMultipleClient
+ */
+ public function testApiCallWithMultiClientAndCustomRegion(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $args['@region'] = 'theRegion';
+
+ $awsClient = $this->getMockBuilder($awsClientClass)
+ ->disableOriginalConstructor()
+ ->setMethods([$method])
+ ->getMock();
+ $awsClient
+ ->expects($this->once())
+ ->method($method)
+ ->with($this->identicalTo($args))
+ ->willReturn(new Result($result));
+
+ $client = new SnsClient($awsClient);
+
+ $actualResult = $client->{$method}($args);
+
+ $this->assertInstanceOf(Result::class, $actualResult);
+ $this->assertSame($result, $actualResult->toArray());
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ */
+ public function testApiCallWithSingleClientAndCustomRegion(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $args['@region'] = 'theRegion';
+
+ $awsClient = $this->getMockBuilder($awsClientClass)
+ ->disableOriginalConstructor()
+ ->setMethods([$method])
+ ->getMock();
+ $awsClient
+ ->expects($this->never())
+ ->method($method)
+ ;
+
+ $client = new SnsClient($awsClient);
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Cannot send message to another region because transport is configured with single aws client');
+ $client->{$method}($args);
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ */
+ public function testApiCallWithMultiClientAndEmptyCustomRegion(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $expectedArgs = $args;
+ $args['@region'] = '';
+
+ $awsClient = $this->getMockBuilder($awsClientClass)
+ ->disableOriginalConstructor()
+ ->setMethods([$method])
+ ->getMock();
+ $awsClient
+ ->expects($this->once())
+ ->method($method)
+ ->with($this->identicalTo($expectedArgs))
+ ->willReturn(new Result($result));
+
+ $client = new SnsClient($awsClient);
+
+ $actualResult = $client->{$method}($args);
+
+ $this->assertInstanceOf(Result::class, $actualResult);
+ $this->assertSame($result, $actualResult->toArray());
+ }
+
+ public function provideApiCallsSingleClient()
+ {
+ yield [
+ 'createTopic',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ AwsSnsClient::class,
+ ];
+
+ yield [
+ 'publish',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ AwsSnsClient::class,
+ ];
+ }
+
+ public function provideApiCallsMultipleClient()
+ {
+ yield [
+ 'createTopic',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ MultiRegionClient::class,
+ ];
+
+ yield [
+ 'publish',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ MultiRegionClient::class,
+ ];
+ }
+}
diff --git a/pkg/sns/Tests/SnsConnectionFactoryConfigTest.php b/pkg/sns/Tests/SnsConnectionFactoryConfigTest.php
new file mode 100644
index 000000000..305a6518d
--- /dev/null
+++ b/pkg/sns/Tests/SnsConnectionFactoryConfigTest.php
@@ -0,0 +1,201 @@
+expectException(\LogicException::class);
+ $this->expectExceptionMessage('The config must be either an array of options, a DSN string, null or instance of Aws\Sns\SnsClient');
+
+ new SnsConnectionFactory(new \stdClass());
+ }
+
+ public function testThrowIfSchemeIsNotAmqp()
+ {
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The given scheme protocol "http" is not supported. It must be "sns"');
+
+ new SnsConnectionFactory('http://example.com');
+ }
+
+ public function testThrowIfDsnCouldNotBeParsed()
+ {
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The DSN is invalid.');
+
+ new SnsConnectionFactory('foo');
+ }
+
+ /**
+ * @dataProvider provideConfigs
+ */
+ public function testShouldParseConfigurationAsExpected($config, $expectedConfig)
+ {
+ $factory = new SnsConnectionFactory($config);
+
+ $this->assertAttributeEquals($expectedConfig, 'config', $factory);
+ }
+
+ public static function provideConfigs()
+ {
+ yield [
+ null,
+ [
+ 'key' => null,
+ 'secret' => null,
+ 'token' => null,
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'lazy' => true,
+ 'endpoint' => null,
+ 'topic_arns' => [],
+ 'http' => [],
+ ],
+ ];
+
+ yield [
+ 'sns:',
+ [
+ 'key' => null,
+ 'secret' => null,
+ 'token' => null,
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'lazy' => true,
+ 'endpoint' => null,
+ 'topic_arns' => [],
+ 'http' => [],
+ ],
+ ];
+
+ yield [
+ [],
+ [
+ 'key' => null,
+ 'secret' => null,
+ 'token' => null,
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'lazy' => true,
+ 'endpoint' => null,
+ 'topic_arns' => [],
+ 'http' => [],
+ ],
+ ];
+
+ yield [
+ 'sns:?key=theKey&secret=theSecret&token=theToken&lazy=0',
+ [
+ 'key' => 'theKey',
+ 'secret' => 'theSecret',
+ 'token' => 'theToken',
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'lazy' => false,
+ 'endpoint' => null,
+ 'topic_arns' => [],
+ 'http' => [],
+ ],
+ ];
+
+ yield [
+ ['dsn' => 'sns:?key=theKey&secret=theSecret&token=theToken&lazy=0'],
+ [
+ 'key' => 'theKey',
+ 'secret' => 'theSecret',
+ 'token' => 'theToken',
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'lazy' => false,
+ 'endpoint' => null,
+ 'topic_arns' => [],
+ 'http' => [],
+ ],
+ ];
+
+ yield [
+ ['key' => 'theKey', 'secret' => 'theSecret', 'token' => 'theToken', 'lazy' => false],
+ [
+ 'key' => 'theKey',
+ 'secret' => 'theSecret',
+ 'token' => 'theToken',
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'lazy' => false,
+ 'endpoint' => null,
+ 'topic_arns' => [],
+ 'http' => [],
+ ],
+ ];
+
+ yield [
+ [
+ 'key' => 'theKey',
+ 'secret' => 'theSecret',
+ 'token' => 'theToken',
+ 'lazy' => false,
+ 'endpoint' => 'http://localstack:1111',
+ ],
+ [
+ 'key' => 'theKey',
+ 'secret' => 'theSecret',
+ 'token' => 'theToken',
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'lazy' => false,
+ 'endpoint' => 'http://localstack:1111',
+ 'topic_arns' => [],
+ 'http' => [],
+ ],
+ ];
+
+ yield [
+ ['dsn' => 'sns:?topic_arns[topic1]=arn:aws:sns:us-east-1:123456789012:topic1&topic_arns[topic2]=arn:aws:sns:us-west-2:123456789012:topic2'],
+ [
+ 'key' => null,
+ 'secret' => null,
+ 'token' => null,
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'lazy' => true,
+ 'endpoint' => null,
+ 'topic_arns' => [
+ 'topic1' => 'arn:aws:sns:us-east-1:123456789012:topic1',
+ 'topic2' => 'arn:aws:sns:us-west-2:123456789012:topic2',
+ ],
+ 'http' => [],
+ ],
+ ];
+
+ yield [
+ ['dsn' => 'sns:?http[timeout]=5&http[connect_timeout]=2'],
+ [
+ 'key' => null,
+ 'secret' => null,
+ 'token' => null,
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'lazy' => true,
+ 'endpoint' => null,
+ 'topic_arns' => [],
+ 'http' => [
+ 'timeout' => '5',
+ 'connect_timeout' => '2',
+ ],
+ ],
+ ];
+ }
+}
diff --git a/pkg/sns/Tests/SnsConnectionFactoryTest.php b/pkg/sns/Tests/SnsConnectionFactoryTest.php
new file mode 100644
index 000000000..4e9ad6ec9
--- /dev/null
+++ b/pkg/sns/Tests/SnsConnectionFactoryTest.php
@@ -0,0 +1,85 @@
+assertClassImplements(ConnectionFactory::class, SnsConnectionFactory::class);
+ }
+
+ public function testCouldBeConstructedWithEmptyConfiguration()
+ {
+ $factory = new SnsConnectionFactory([]);
+
+ $this->assertAttributeEquals([
+ 'lazy' => true,
+ 'key' => null,
+ 'secret' => null,
+ 'token' => null,
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'endpoint' => null,
+ 'topic_arns' => [],
+ 'http' => [],
+ ], 'config', $factory);
+ }
+
+ public function testCouldBeConstructedWithCustomConfiguration()
+ {
+ $factory = new SnsConnectionFactory(['key' => 'theKey']);
+
+ $this->assertAttributeEquals([
+ 'lazy' => true,
+ 'key' => 'theKey',
+ 'secret' => null,
+ 'token' => null,
+ 'region' => null,
+ 'version' => '2010-03-31',
+ 'endpoint' => null,
+ 'topic_arns' => [],
+ 'http' => [],
+ ], 'config', $factory);
+ }
+
+ public function testCouldBeConstructedWithClient()
+ {
+ $awsClient = $this->createMock(AwsSnsClient::class);
+
+ $factory = new SnsConnectionFactory($awsClient);
+
+ $context = $factory->createContext();
+
+ $this->assertInstanceOf(SnsContext::class, $context);
+
+ $client = $this->readAttribute($context, 'client');
+ $this->assertInstanceOf(SnsClient::class, $client);
+ $this->assertAttributeSame($awsClient, 'inputClient', $client);
+ }
+
+ public function testShouldCreateLazyContext()
+ {
+ $factory = new SnsConnectionFactory(['lazy' => true]);
+
+ $context = $factory->createContext();
+
+ $this->assertInstanceOf(SnsContext::class, $context);
+
+ $client = $this->readAttribute($context, 'client');
+ $this->assertInstanceOf(SnsClient::class, $client);
+ $this->assertAttributeInstanceOf(\Closure::class, 'inputClient', $client);
+ }
+}
diff --git a/pkg/sns/Tests/SnsDestinationTest.php b/pkg/sns/Tests/SnsDestinationTest.php
new file mode 100644
index 000000000..c9f9669e7
--- /dev/null
+++ b/pkg/sns/Tests/SnsDestinationTest.php
@@ -0,0 +1,52 @@
+assertClassImplements(Topic::class, SnsDestination::class);
+ $this->assertClassImplements(Queue::class, SnsDestination::class);
+ }
+
+ public function testShouldReturnNameSetInConstructor()
+ {
+ $destination = new SnsDestination('aDestinationName');
+
+ $this->assertSame('aDestinationName', $destination->getQueueName());
+ $this->assertSame('aDestinationName', $destination->getTopicName());
+ }
+
+ public function testCouldSetPolicyAttribute()
+ {
+ $destination = new SnsDestination('aDestinationName');
+ $destination->setPolicy('thePolicy');
+
+ $this->assertSame(['Policy' => 'thePolicy'], $destination->getAttributes());
+ }
+
+ public function testCouldSetDisplayNameAttribute()
+ {
+ $destination = new SnsDestination('aDestinationName');
+ $destination->setDisplayName('theDisplayName');
+
+ $this->assertSame(['DisplayName' => 'theDisplayName'], $destination->getAttributes());
+ }
+
+ public function testCouldSetDeliveryPolicyAttribute()
+ {
+ $destination = new SnsDestination('aDestinationName');
+ $destination->setDeliveryPolicy(123);
+
+ $this->assertSame(['DeliveryPolicy' => 123], $destination->getAttributes());
+ }
+}
diff --git a/pkg/sns/Tests/SnsProducerTest.php b/pkg/sns/Tests/SnsProducerTest.php
new file mode 100644
index 000000000..1c6be7f85
--- /dev/null
+++ b/pkg/sns/Tests/SnsProducerTest.php
@@ -0,0 +1,245 @@
+assertClassImplements(Producer::class, SnsProducer::class);
+ }
+
+ public function testShouldThrowIfBodyOfInvalidType()
+ {
+ $this->expectException(InvalidMessageException::class);
+ $this->expectExceptionMessage('The message body must be a non-empty string.');
+
+ $producer = new SnsProducer($this->createSnsContextMock());
+
+ $message = new SnsMessage('');
+
+ $producer->send(new SnsDestination(''), $message);
+ }
+
+ public function testShouldThrowIfDestinationOfInvalidType()
+ {
+ $this->expectException(InvalidDestinationException::class);
+ $this->expectExceptionMessage('The destination must be an instance of Enqueue\Sns\SnsDestination but got Mock_Destinat');
+
+ $producer = new SnsProducer($this->createSnsContextMock());
+
+ $producer->send($this->createMock(Destination::class), new SnsMessage());
+ }
+
+ public function testShouldThrowIfPublishFailed()
+ {
+ $destination = new SnsDestination('queue-name');
+
+ $client = $this->createSnsClientMock();
+ $client
+ ->expects($this->once())
+ ->method('publish')
+ ->willReturn(new Result())
+ ;
+
+ $context = $this->createSnsContextMock();
+ $context
+ ->expects($this->once())
+ ->method('getTopicArn')
+ ->with($this->identicalTo($destination))
+ ->willReturn('theTopicArn')
+ ;
+ $context
+ ->expects($this->once())
+ ->method('getSnsClient')
+ ->willReturn($client)
+ ;
+
+ $message = new SnsMessage('foo');
+
+ $this->expectException(\RuntimeException::class);
+ $this->expectExceptionMessage('Message was not sent');
+
+ $producer = new SnsProducer($context);
+ $producer->send($destination, $message);
+ }
+
+ public function testShouldThrowIfsetTimeToLiveIsNotNull()
+ {
+ $this->expectException(TimeToLiveNotSupportedException::class);
+
+ $producer = new SnsProducer($this->createSnsContextMock());
+ $result = $producer->setTimeToLive();
+
+ $this->assertInstanceOf(SnsProducer::class, $result);
+
+ $this->expectExceptionMessage('The provider does not support time to live feature');
+
+ $producer->setTimeToLive(200);
+ }
+
+ public function testShouldThrowIfsetPriorityIsNotNull()
+ {
+ $this->expectException(PriorityNotSupportedException::class);
+
+ $producer = new SnsProducer($this->createSnsContextMock());
+ $result = $producer->setPriority();
+
+ $this->assertInstanceOf(SnsProducer::class, $result);
+
+ $this->expectExceptionMessage('The provider does not support priority feature');
+
+ $producer->setPriority(200);
+ }
+
+ public function testShouldThrowIfsetDeliveryDelayIsNotNull()
+ {
+ $this->expectException(DeliveryDelayNotSupportedException::class);
+
+ $producer = new SnsProducer($this->createSnsContextMock());
+ $result = $producer->setDeliveryDelay();
+
+ $this->assertInstanceOf(SnsProducer::class, $result);
+
+ $this->expectExceptionMessage('The provider does not support delivery delay feature');
+
+ $producer->setDeliveryDelay(200);
+ }
+
+ public function testShouldPublish()
+ {
+ $destination = new SnsDestination('queue-name');
+
+ $expectedArguments = [
+ 'Message' => 'theBody',
+ 'MessageAttributes' => [
+ 'Headers' => [
+ 'DataType' => 'String',
+ 'StringValue' => '[{"hkey":"hvaleu"},{"key":"value"}]',
+ ],
+ ],
+ 'TopicArn' => 'theTopicArn',
+ ];
+
+ $client = $this->createSnsClientMock();
+ $client
+ ->expects($this->once())
+ ->method('publish')
+ ->with($this->identicalTo($expectedArguments))
+ ->willReturn(new Result(['MessageId' => 'theMessageId']))
+ ;
+
+ $context = $this->createSnsContextMock();
+ $context
+ ->expects($this->once())
+ ->method('getTopicArn')
+ ->with($this->identicalTo($destination))
+ ->willReturn('theTopicArn')
+ ;
+ $context
+ ->expects($this->once())
+ ->method('getSnsClient')
+ ->willReturn($client)
+ ;
+
+ $message = new SnsMessage('theBody', ['key' => 'value'], ['hkey' => 'hvaleu']);
+
+ $producer = new SnsProducer($context);
+ $producer->send($destination, $message);
+ }
+
+ /**
+ * @throws InvalidMessageException
+ */
+ public function testShouldPublishWithMergedAttributes()
+ {
+ $context = $this->createSnsContextMock();
+ $client = $this->createSnsClientMock();
+
+ $context
+ ->expects($this->once())
+ ->method('getSnsClient')
+ ->willReturn($client);
+
+ $expectedArgument = [
+ 'Message' => 'message',
+ 'MessageAttributes' => [
+ 'Headers' => [
+ 'DataType' => 'String',
+ 'StringValue' => '[[],[]]',
+ ],
+ 'Foo' => [
+ 'DataType' => 'String',
+ 'StringValue' => 'foo-value',
+ ],
+ 'Bar' => [
+ 'DataType' => 'Binary',
+ 'BinaryValue' => 'bar-val',
+ ],
+ ],
+ 'TopicArn' => '',
+ 'MessageStructure' => 'structure',
+ 'PhoneNumber' => 'phone',
+ 'Subject' => 'subject',
+ 'TargetArn' => 'target_arn',
+ ];
+
+ $client
+ ->expects($this->once())
+ ->method('publish')
+ ->with($this->identicalTo($expectedArgument))
+ ->willReturn(new Result(['MessageId' => 'theMessageId']));
+
+ $attributes = [
+ 'Foo' => [
+ 'DataType' => 'String',
+ 'StringValue' => 'foo-value',
+ ],
+ ];
+
+ $message = new SnsMessage(
+ 'message', [], [], $attributes, 'structure', 'phone',
+ 'subject', 'target_arn'
+ );
+ $message->addAttribute('Bar', 'Binary', 'bar-val');
+
+ $destination = new SnsDestination('queue-name');
+
+ $producer = new SnsProducer($context);
+ $producer->send($destination, $message);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|SnsContext
+ */
+ private function createSnsContextMock(): SnsContext
+ {
+ return $this->createMock(SnsContext::class);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|SnsClient
+ */
+ private function createSnsClientMock(): SnsClient
+ {
+ return $this->createMock(SnsClient::class);
+ }
+}
diff --git a/pkg/sns/Tests/Spec/SnsConnectionFactoryTest.php b/pkg/sns/Tests/Spec/SnsConnectionFactoryTest.php
new file mode 100644
index 000000000..20008bc04
--- /dev/null
+++ b/pkg/sns/Tests/Spec/SnsConnectionFactoryTest.php
@@ -0,0 +1,18 @@
+expectException(\LogicException::class);
+ $this->expectExceptionMessage('SNS transport does not support consumption. You should consider using SQS instead.');
+
+ parent::testShouldCreateConsumerOnCreateConsumerMethodCall();
+ }
+
+ public function testSetsSubscriptionAttributes(): void
+ {
+ $client = $this->createMock(SnsClient::class);
+ $client->expects($this->once())
+ ->method('listSubscriptionsByTopic')
+ ->willReturn(new Result(['Subscriptions' => [
+ ['SubscriptionArn' => 'arn1'],
+ ['SubscriptionArn' => 'arn2'],
+ ]]));
+ $client->expects($this->exactly(2))
+ ->method('setSubscriptionAttributes')
+ ->withConsecutive(
+ [$this->equalTo(['attr1' => 'value1', 'SubscriptionArn' => 'arn1'])],
+ [$this->equalTo(['attr1' => 'value1', 'SubscriptionArn' => 'arn2'])],
+ );
+
+ $context = new SnsContext($client, ['topic_arns' => ['topic1' => 'topicArn1']]);
+ $context->setSubscriptionAttributes(new SnsSubscribe(
+ new SnsDestination('topic1'),
+ 'endpoint1',
+ 'protocol1',
+ false,
+ ['attr1' => 'value1'],
+ ));
+ }
+
+ protected function createContext()
+ {
+ $client = $this->createMock(SnsClient::class);
+
+ return new SnsContext($client, ['topic_arns' => []]);
+ }
+}
diff --git a/pkg/sns/Tests/Spec/SnsMessageTest.php b/pkg/sns/Tests/Spec/SnsMessageTest.php
new file mode 100644
index 000000000..af24344e6
--- /dev/null
+++ b/pkg/sns/Tests/Spec/SnsMessageTest.php
@@ -0,0 +1,14 @@
+createMock(SnsContext::class));
+ }
+}
diff --git a/pkg/sns/Tests/Spec/SnsQueueTest.php b/pkg/sns/Tests/Spec/SnsQueueTest.php
new file mode 100644
index 000000000..39c0e5513
--- /dev/null
+++ b/pkg/sns/Tests/Spec/SnsQueueTest.php
@@ -0,0 +1,14 @@
+createContext();
+
+$queue = $context->createQueue('enqueue');
+$consumer = $context->createConsumer($queue);
+
+while (true) {
+ if ($m = $consumer->receive(20000)) {
+ $consumer->acknowledge($m);
+ echo 'Received message: '.$m->getBody().\PHP_EOL;
+ }
+}
+
+echo 'Done'."\n";
diff --git a/pkg/sns/examples/produce.php b/pkg/sns/examples/produce.php
new file mode 100644
index 000000000..3e59c5232
--- /dev/null
+++ b/pkg/sns/examples/produce.php
@@ -0,0 +1,34 @@
+ getenv('ENQUEUE_AWS__SQS__KEY'),
+ 'secret' => getenv('ENQUEUE_AWS__SQS__SECRET'),
+ 'region' => getenv('ENQUEUE_AWS__SQS__REGION'),
+]);
+$context = $factory->createContext();
+
+$topic = $context->createTopic('test_enqueue');
+$context->declareTopic($topic);
+
+$message = $context->createMessage('a_body');
+$message->setProperty('aProp', 'aPropVal');
+$message->setHeader('aHeader', 'aHeaderVal');
+
+$context->createProducer()->send($topic, $message);
diff --git a/pkg/sns/phpunit.xml.dist b/pkg/sns/phpunit.xml.dist
new file mode 100644
index 000000000..5f01f5897
--- /dev/null
+++ b/pkg/sns/phpunit.xml.dist
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+ ./Tests
+
+
+
+
+
+ .
+
+ ./vendor
+ ./Tests
+
+
+
+
diff --git a/pkg/snsqs/.gitattributes b/pkg/snsqs/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/snsqs/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/snsqs/.github/workflows/ci.yml b/pkg/snsqs/.github/workflows/ci.yml
new file mode 100644
index 000000000..c91cb39ab
--- /dev/null
+++ b/pkg/snsqs/.github/workflows/ci.yml
@@ -0,0 +1,29 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/snsqs/.gitignore b/pkg/snsqs/.gitignore
new file mode 100644
index 000000000..a770439e5
--- /dev/null
+++ b/pkg/snsqs/.gitignore
@@ -0,0 +1,6 @@
+*~
+/composer.lock
+/composer.phar
+/phpunit.xml
+/vendor/
+/.idea/
diff --git a/pkg/snsqs/LICENSE b/pkg/snsqs/LICENSE
new file mode 100644
index 000000000..20211e5fd
--- /dev/null
+++ b/pkg/snsqs/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+Copyright (c) 2018 Max Kotliar
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished
+to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/pkg/snsqs/README.md b/pkg/snsqs/README.md
new file mode 100644
index 000000000..94a22776d
--- /dev/null
+++ b/pkg/snsqs/README.md
@@ -0,0 +1,28 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
+# Amazon SNS-SQS Transport
+
+[](https://gitter.im/php-enqueue/Lobby)
+[](https://github.com/php-enqueue/snsqs/actions?query=workflow%3ACI)
+[](https://packagist.org/packages/enqueue/snsqs)
+[](https://packagist.org/packages/enqueue/snsqs)
+
+This is an implementation of Queue Interop specification. It allows you to send and consume message using [Amazon SNS-SQS](https://aws.amazon.com/snsqs/) service.
+
+## Resources
+
+* [Site](https://enqueue.forma-pro.com/)
+* [Documentation](https://php-enqueue.github.io/transport/snsqs/)
+* [Questions](https://gitter.im/php-enqueue/Lobby)
+* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
+
+## License
+
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/snsqs/SnsQsConnectionFactory.php b/pkg/snsqs/SnsQsConnectionFactory.php
new file mode 100644
index 000000000..65812beb3
--- /dev/null
+++ b/pkg/snsqs/SnsQsConnectionFactory.php
@@ -0,0 +1,114 @@
+ null AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
+ * 'secret' => null, AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
+ * 'token' => null, AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
+ * 'region' => null, (string, required) Region to connect to. See http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of available regions.
+ * 'version' => '2012-11-05', (string, required) The version of the webservice to utilize
+ * 'lazy' => true, Enable lazy connection (boolean)
+ * 'endpoint' => null (string, default=null) The full URI of the webservice. This is only required when connecting to a custom endpoint e.g. localstack
+ * ].
+ *
+ * or
+ *
+ * $config = [
+ * 'sns_key' => null, SNS option
+ * 'sqs_secret' => null, SQS option
+ * 'token' Option for both SNS and SQS
+ * ].
+ *
+ * or
+ *
+ * snsqs:
+ * snsqs:?key=aKey&secret=aSecret&sns_token=aSnsToken&sqs_token=aSqsToken
+ *
+ * @param array|string|null $config
+ */
+ public function __construct($config = 'snsqs:')
+ {
+ if (empty($config)) {
+ $this->snsConfig = [];
+ $this->sqsConfig = [];
+ } elseif (is_string($config)) {
+ $this->parseDsn($config);
+ } elseif (is_array($config)) {
+ if (array_key_exists('dsn', $config)) {
+ $this->parseDsn($config['dsn']);
+ } else {
+ $this->parseOptions($config);
+ }
+ } else {
+ throw new \LogicException('The config must be either an array of options, a DSN string or null');
+ }
+ }
+
+ /**
+ * @return SnsQsContext
+ */
+ public function createContext(): Context
+ {
+ return new SnsQsContext(function () {
+ return (new SnsConnectionFactory($this->snsConfig))->createContext();
+ }, function () {
+ return (new SqsConnectionFactory($this->sqsConfig))->createContext();
+ });
+ }
+
+ private function parseDsn(string $dsn): void
+ {
+ $dsn = Dsn::parseFirst($dsn);
+
+ if ('snsqs' !== $dsn->getSchemeProtocol()) {
+ throw new \LogicException(sprintf('The given scheme protocol "%s" is not supported. It must be "snsqs"', $dsn->getSchemeProtocol()));
+ }
+
+ $this->parseOptions($dsn->getQuery());
+ }
+
+ private function parseOptions(array $options): void
+ {
+ // set default options
+ foreach ($options as $key => $value) {
+ if (false === in_array(substr($key, 0, 4), ['sns_', 'sqs_'], true)) {
+ $this->snsConfig[$key] = $value;
+ $this->sqsConfig[$key] = $value;
+ }
+ }
+
+ // set transport specific options
+ foreach ($options as $key => $value) {
+ switch (substr($key, 0, 4)) {
+ case 'sns_':
+ $this->snsConfig[substr($key, 4)] = $value;
+ break;
+ case 'sqs_':
+ $this->sqsConfig[substr($key, 4)] = $value;
+ break;
+ }
+ }
+ }
+}
diff --git a/pkg/snsqs/SnsQsConsumer.php b/pkg/snsqs/SnsQsConsumer.php
new file mode 100644
index 000000000..45237d145
--- /dev/null
+++ b/pkg/snsqs/SnsQsConsumer.php
@@ -0,0 +1,143 @@
+context = $context;
+ $this->consumer = $consumer;
+ $this->queue = $queue;
+ }
+
+ public function getVisibilityTimeout(): ?int
+ {
+ return $this->consumer->getVisibilityTimeout();
+ }
+
+ /**
+ * The duration (in seconds) that the received messages are hidden from subsequent retrieve
+ * requests after being retrieved by a ReceiveMessage request.
+ */
+ public function setVisibilityTimeout(?int $visibilityTimeout = null): void
+ {
+ $this->consumer->setVisibilityTimeout($visibilityTimeout);
+ }
+
+ public function getMaxNumberOfMessages(): int
+ {
+ return $this->consumer->getMaxNumberOfMessages();
+ }
+
+ /**
+ * The maximum number of messages to return. Amazon SQS never returns more messages than this value
+ * (however, fewer messages might be returned). Valid values are 1 to 10. Default is 1.
+ */
+ public function setMaxNumberOfMessages(int $maxNumberOfMessages): void
+ {
+ $this->consumer->setMaxNumberOfMessages($maxNumberOfMessages);
+ }
+
+ public function getQueue(): Queue
+ {
+ return $this->queue;
+ }
+
+ public function receive(int $timeout = 0): ?Message
+ {
+ if ($sqsMessage = $this->consumer->receive($timeout)) {
+ return $this->convertMessage($sqsMessage);
+ }
+
+ return null;
+ }
+
+ public function receiveNoWait(): ?Message
+ {
+ if ($sqsMessage = $this->consumer->receiveNoWait()) {
+ return $this->convertMessage($sqsMessage);
+ }
+
+ return null;
+ }
+
+ /**
+ * @param SnsQsMessage $message
+ */
+ public function acknowledge(Message $message): void
+ {
+ InvalidMessageException::assertMessageInstanceOf($message, SnsQsMessage::class);
+
+ $this->consumer->acknowledge($message->getSqsMessage());
+ }
+
+ /**
+ * @param SnsQsMessage $message
+ */
+ public function reject(Message $message, bool $requeue = false): void
+ {
+ InvalidMessageException::assertMessageInstanceOf($message, SnsQsMessage::class);
+
+ $this->consumer->reject($message->getSqsMessage(), $requeue);
+ }
+
+ private function convertMessage(SqsMessage $sqsMessage): SnsQsMessage
+ {
+ $message = $this->context->createMessage();
+ $message->setRedelivered($sqsMessage->isRedelivered());
+ $message->setSqsMessage($sqsMessage);
+
+ $body = $sqsMessage->getBody();
+
+ if (isset($body[0]) && '{' === $body[0]) {
+ $data = json_decode($sqsMessage->getBody(), true);
+
+ if (isset($data['TopicArn']) && isset($data['Type']) && 'Notification' === $data['Type']) {
+ // SNS message conversion
+ if (isset($data['Message'])) {
+ $message->setBody((string) $data['Message']);
+ }
+
+ if (isset($data['MessageAttributes']['Headers'])) {
+ $headersData = json_decode($data['MessageAttributes']['Headers']['Value'], true);
+
+ $message->setHeaders($headersData[0]);
+ $message->setProperties($headersData[1]);
+ }
+
+ return $message;
+ }
+ }
+
+ $message->setBody($sqsMessage->getBody());
+ $message->setHeaders($sqsMessage->getHeaders());
+ $message->setProperties($sqsMessage->getProperties());
+
+ return $message;
+ }
+}
diff --git a/pkg/snsqs/SnsQsContext.php b/pkg/snsqs/SnsQsContext.php
new file mode 100644
index 000000000..d26a0fc6d
--- /dev/null
+++ b/pkg/snsqs/SnsQsContext.php
@@ -0,0 +1,214 @@
+snsContext = $snsContext;
+ } elseif (is_callable($snsContext)) {
+ $this->snsContextFactory = $snsContext;
+ } else {
+ throw new \InvalidArgumentException(sprintf('The $snsContext argument must be either %s or callable that returns %s once called.', SnsContext::class, SnsContext::class));
+ }
+
+ if ($sqsContext instanceof SqsContext) {
+ $this->sqsContext = $sqsContext;
+ } elseif (is_callable($sqsContext)) {
+ $this->sqsContextFactory = $sqsContext;
+ } else {
+ throw new \InvalidArgumentException(sprintf('The $sqsContext argument must be either %s or callable that returns %s once called.', SqsContext::class, SqsContext::class));
+ }
+ }
+
+ /**
+ * @return SnsQsMessage
+ */
+ public function createMessage(string $body = '', array $properties = [], array $headers = []): Message
+ {
+ return new SnsQsMessage($body, $properties, $headers);
+ }
+
+ /**
+ * @return SnsQsTopic
+ */
+ public function createTopic(string $topicName): Topic
+ {
+ return new SnsQsTopic($topicName);
+ }
+
+ /**
+ * @return SnsQsQueue
+ */
+ public function createQueue(string $queueName): Queue
+ {
+ return new SnsQsQueue($queueName);
+ }
+
+ public function createTemporaryQueue(): Queue
+ {
+ throw TemporaryQueueNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function createProducer(): Producer
+ {
+ return new SnsQsProducer($this->getSnsContext(), $this->getSqsContext());
+ }
+
+ /**
+ * @param SnsQsQueue $destination
+ */
+ public function createConsumer(Destination $destination): Consumer
+ {
+ InvalidDestinationException::assertDestinationInstanceOf($destination, SnsQsQueue::class);
+
+ return new SnsQsConsumer($this, $this->getSqsContext()->createConsumer($destination), $destination);
+ }
+
+ /**
+ * @param SnsQsQueue $queue
+ */
+ public function purgeQueue(Queue $queue): void
+ {
+ InvalidDestinationException::assertDestinationInstanceOf($queue, SnsQsQueue::class);
+
+ $this->getSqsContext()->purgeQueue($queue);
+ }
+
+ public function createSubscriptionConsumer(): SubscriptionConsumer
+ {
+ throw SubscriptionConsumerNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function declareTopic(SnsQsTopic $topic): void
+ {
+ $this->getSnsContext()->declareTopic($topic);
+ }
+
+ public function setTopicArn(SnsQsTopic $topic, string $arn): void
+ {
+ $this->getSnsContext()->setTopicArn($topic, $arn);
+ }
+
+ public function deleteTopic(SnsQsTopic $topic): void
+ {
+ $this->getSnsContext()->deleteTopic($topic);
+ }
+
+ public function declareQueue(SnsQsQueue $queue): void
+ {
+ $this->getSqsContext()->declareQueue($queue);
+ }
+
+ public function deleteQueue(SnsQsQueue $queue): void
+ {
+ $this->getSqsContext()->deleteQueue($queue);
+ }
+
+ public function bind(SnsQsTopic $topic, SnsQsQueue $queue): void
+ {
+ $this->getSnsContext()->subscribe(new SnsSubscribe(
+ $topic,
+ $this->getSqsContext()->getQueueArn($queue),
+ SnsSubscribe::PROTOCOL_SQS
+ ));
+ }
+
+ public function unbind(SnsQsTopic $topic, SnsQsQueue $queue): void
+ {
+ $this->getSnsContext()->unsubscibe(new SnsUnsubscribe(
+ $topic,
+ $this->getSqsContext()->getQueueArn($queue),
+ SnsSubscribe::PROTOCOL_SQS
+ ));
+ }
+
+ public function close(): void
+ {
+ $this->getSnsContext()->close();
+ $this->getSqsContext()->close();
+ }
+
+ public function setSubscriptionAttributes(SnsQsTopic $topic, SnsQsQueue $queue, array $attributes): void
+ {
+ $this->getSnsContext()->setSubscriptionAttributes(new SnsSubscribe(
+ $topic,
+ $this->getSqsContext()->getQueueArn($queue),
+ SnsSubscribe::PROTOCOL_SQS,
+ false,
+ $attributes,
+ ));
+ }
+
+ private function getSnsContext(): SnsContext
+ {
+ if (null === $this->snsContext) {
+ $context = call_user_func($this->snsContextFactory);
+ if (false == $context instanceof SnsContext) {
+ throw new \LogicException(sprintf('The factory must return instance of %s. It returned %s', SnsContext::class, is_object($context) ? $context::class : gettype($context)));
+ }
+
+ $this->snsContext = $context;
+ }
+
+ return $this->snsContext;
+ }
+
+ private function getSqsContext(): SqsContext
+ {
+ if (null === $this->sqsContext) {
+ $context = call_user_func($this->sqsContextFactory);
+ if (false == $context instanceof SqsContext) {
+ throw new \LogicException(sprintf('The factory must return instance of %s. It returned %s', SqsContext::class, is_object($context) ? $context::class : gettype($context)));
+ }
+
+ $this->sqsContext = $context;
+ }
+
+ return $this->sqsContext;
+ }
+}
diff --git a/pkg/snsqs/SnsQsMessage.php b/pkg/snsqs/SnsQsMessage.php
new file mode 100644
index 000000000..900ad9125
--- /dev/null
+++ b/pkg/snsqs/SnsQsMessage.php
@@ -0,0 +1,108 @@
+body = $body;
+ $this->properties = $properties;
+ $this->headers = $headers;
+ $this->redelivered = false;
+ $this->messageAttributes = $messageAttributes;
+ }
+
+ public function setSqsMessage(SqsMessage $message): void
+ {
+ $this->sqsMessage = $message;
+ }
+
+ public function getSqsMessage(): SqsMessage
+ {
+ return $this->sqsMessage;
+ }
+
+ public function getMessageAttributes(): ?array
+ {
+ return $this->messageAttributes;
+ }
+
+ public function setMessageAttributes(?array $messageAttributes): void
+ {
+ $this->messageAttributes = $messageAttributes;
+ }
+
+ /**
+ * Only FIFO.
+ *
+ * The token used for deduplication of sent messages. If a message with a particular MessageDeduplicationId is sent successfully,
+ * any messages sent with the same MessageDeduplicationId are accepted successfully but aren't delivered during the 5-minute
+ * deduplication interval. For more information, see http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing.
+ */
+ public function setMessageDeduplicationId(?string $id = null): void
+ {
+ $this->messageDeduplicationId = $id;
+ }
+
+ public function getMessageDeduplicationId(): ?string
+ {
+ return $this->messageDeduplicationId;
+ }
+
+ /**
+ * Only FIFO.
+ *
+ * The tag that specifies that a message belongs to a specific message group. Messages that belong to the same message group
+ * are processed in a FIFO manner (however, messages in different message groups might be processed out of order).
+ * To interleave multiple ordered streams within a single queue, use MessageGroupId values (for example, session data
+ * for multiple users). In this scenario, multiple readers can process the queue, but the session data
+ * of each user is processed in a FIFO fashion.
+ */
+ public function setMessageGroupId(?string $id = null): void
+ {
+ $this->messageGroupId = $id;
+ }
+
+ public function getMessageGroupId(): ?string
+ {
+ return $this->messageGroupId;
+ }
+}
diff --git a/pkg/snsqs/SnsQsProducer.php b/pkg/snsqs/SnsQsProducer.php
new file mode 100644
index 000000000..a80e1eb2b
--- /dev/null
+++ b/pkg/snsqs/SnsQsProducer.php
@@ -0,0 +1,143 @@
+snsContext = $snsContext;
+ $this->sqsContext = $sqsContext;
+ }
+
+ /**
+ * @param SnsQsTopic $destination
+ * @param SnsQsMessage $message
+ */
+ public function send(Destination $destination, Message $message): void
+ {
+ InvalidMessageException::assertMessageInstanceOf($message, SnsQsMessage::class);
+
+ if (false == $destination instanceof SnsQsTopic && false == $destination instanceof SnsQsQueue) {
+ throw new InvalidDestinationException(sprintf('The destination must be an instance of [%s|%s] but got %s.', SnsQsTopic::class, SnsQsQueue::class, is_object($destination) ? $destination::class : gettype($destination)));
+ }
+
+ if ($destination instanceof SnsQsTopic) {
+ $snsMessage = $this->snsContext->createMessage(
+ $message->getBody(),
+ $message->getProperties(),
+ $message->getHeaders()
+ );
+ $snsMessage->setMessageAttributes($message->getMessageAttributes());
+ $snsMessage->setMessageGroupId($message->getMessageGroupId());
+ $snsMessage->setMessageDeduplicationId($message->getMessageDeduplicationId());
+
+ $this->getSnsProducer()->send($destination, $snsMessage);
+ } else {
+ $sqsMessage = $this->sqsContext->createMessage(
+ $message->getBody(),
+ $message->getProperties(),
+ $message->getHeaders()
+ );
+
+ $sqsMessage->setMessageGroupId($message->getMessageGroupId());
+ $sqsMessage->setMessageDeduplicationId($message->getMessageDeduplicationId());
+
+ $this->getSqsProducer()->send($destination, $sqsMessage);
+ }
+ }
+
+ /**
+ * Delivery delay is supported by SQSProducer.
+ */
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
+ {
+ $this->getSqsProducer()->setDeliveryDelay($deliveryDelay);
+
+ return $this;
+ }
+
+ /**
+ * Delivery delay is supported by SQSProducer.
+ */
+ public function getDeliveryDelay(): ?int
+ {
+ return $this->getSqsProducer()->getDeliveryDelay();
+ }
+
+ public function setPriority(?int $priority = null): Producer
+ {
+ $this->getSnsProducer()->setPriority($priority);
+ $this->getSqsProducer()->setPriority($priority);
+
+ return $this;
+ }
+
+ public function getPriority(): ?int
+ {
+ return $this->getSnsProducer()->getPriority();
+ }
+
+ public function setTimeToLive(?int $timeToLive = null): Producer
+ {
+ $this->getSnsProducer()->setTimeToLive($timeToLive);
+ $this->getSqsProducer()->setTimeToLive($timeToLive);
+
+ return $this;
+ }
+
+ public function getTimeToLive(): ?int
+ {
+ return $this->getSnsProducer()->getTimeToLive();
+ }
+
+ private function getSnsProducer(): SnsProducer
+ {
+ if (null === $this->snsProducer) {
+ $this->snsProducer = $this->snsContext->createProducer();
+ }
+
+ return $this->snsProducer;
+ }
+
+ private function getSqsProducer(): SqsProducer
+ {
+ if (null === $this->sqsProducer) {
+ $this->sqsProducer = $this->sqsContext->createProducer();
+ }
+
+ return $this->sqsProducer;
+ }
+}
diff --git a/pkg/snsqs/SnsQsQueue.php b/pkg/snsqs/SnsQsQueue.php
new file mode 100644
index 000000000..92c3a542b
--- /dev/null
+++ b/pkg/snsqs/SnsQsQueue.php
@@ -0,0 +1,11 @@
+createMock(SnsQsContext::class);
+ $context->expects($this->once())
+ ->method('createMessage')
+ ->willReturn(new SnsQsMessage());
+
+ $sqsConsumer = $this->createMock(SqsConsumer::class);
+ $sqsConsumer->expects($this->once())
+ ->method('receive')
+ ->willReturn(new SqsMessage(json_encode([
+ 'Type' => 'Notification',
+ 'TopicArn' => 'arn:aws:sns:us-east-2:12345:topic-name',
+ 'Message' => 'The Body',
+ 'MessageAttributes' => [
+ 'Headers' => [
+ 'Type' => 'String',
+ 'Value' => '[{"headerKey":"headerVal"},{"propKey": "propVal"}]',
+ ],
+ ],
+ ])));
+
+ $consumer = new SnsQsConsumer($context, $sqsConsumer, new SnsQsQueue('queue'));
+ $result = $consumer->receive();
+
+ $this->assertInstanceOf(SnsQsMessage::class, $result);
+ $this->assertSame('The Body', $result->getBody());
+ $this->assertSame(['headerKey' => 'headerVal'], $result->getHeaders());
+ $this->assertSame(['propKey' => 'propVal'], $result->getProperties());
+ }
+
+ public function testReceivesSqsMessage(): void
+ {
+ $context = $this->createMock(SnsQsContext::class);
+ $context->expects($this->once())
+ ->method('createMessage')
+ ->willReturn(new SnsQsMessage());
+
+ $sqsConsumer = $this->createMock(SqsConsumer::class);
+ $sqsConsumer->expects($this->once())
+ ->method('receive')
+ ->willReturn(new SqsMessage(
+ 'The Body',
+ ['propKey' => 'propVal'],
+ ['headerKey' => 'headerVal'],
+ ));
+
+ $consumer = new SnsQsConsumer($context, $sqsConsumer, new SnsQsQueue('queue'));
+ $result = $consumer->receive();
+
+ $this->assertInstanceOf(SnsQsMessage::class, $result);
+ $this->assertSame('The Body', $result->getBody());
+ $this->assertSame(['headerKey' => 'headerVal'], $result->getHeaders());
+ $this->assertSame(['propKey' => 'propVal'], $result->getProperties());
+ }
+}
diff --git a/pkg/snsqs/Tests/SnsQsProducerTest.php b/pkg/snsqs/Tests/SnsQsProducerTest.php
new file mode 100644
index 000000000..59798dc11
--- /dev/null
+++ b/pkg/snsqs/Tests/SnsQsProducerTest.php
@@ -0,0 +1,203 @@
+assertClassImplements(Producer::class, SnsQsProducer::class);
+ }
+
+ public function testShouldThrowIfMessageIsInvalidType()
+ {
+ $this->expectException(InvalidMessageException::class);
+ $this->expectExceptionMessage('The message must be an instance of Enqueue\SnsQs\SnsQsMessage but it is Double\Message\P4');
+
+ $producer = new SnsQsProducer($this->createSnsContextMock(), $this->createSqsContextMock());
+
+ $message = $this->prophesize(Message::class)->reveal();
+
+ $producer->send(new SnsQsTopic(''), $message);
+ }
+
+ public function testShouldThrowIfDestinationOfInvalidType()
+ {
+ $this->expectException(InvalidDestinationException::class);
+
+ $producer = new SnsQsProducer($this->createSnsContextMock(), $this->createSqsContextMock());
+
+ $destination = $this->prophesize(Destination::class)->reveal();
+
+ $producer->send($destination, new SnsQsMessage());
+ }
+
+ public function testShouldSetDeliveryDelayToSQSProducer()
+ {
+ $delay = 10;
+
+ $sqsProducerStub = $this->prophesize(SqsProducer::class);
+ $sqsProducerStub->setDeliveryDelay(Argument::is($delay))->shouldBeCalledTimes(1);
+
+ $sqsMock = $this->createSqsContextMock();
+ $sqsMock->method('createProducer')->willReturn($sqsProducerStub->reveal());
+
+ $producer = new SnsQsProducer($this->createSnsContextMock(), $sqsMock);
+
+ $producer->setDeliveryDelay($delay);
+ }
+
+ public function testShouldGetDeliveryDelayFromSQSProducer()
+ {
+ $delay = 10;
+
+ $sqsProducerStub = $this->prophesize(SqsProducer::class);
+ $sqsProducerStub->getDeliveryDelay()->willReturn($delay);
+
+ $sqsMock = $this->createSqsContextMock();
+ $sqsMock->method('createProducer')->willReturn($sqsProducerStub->reveal());
+
+ $producer = new SnsQsProducer($this->createSnsContextMock(), $sqsMock);
+
+ $this->assertEquals($delay, $producer->getDeliveryDelay());
+ }
+
+ public function testShouldSendSnsTopicMessageToSnsProducer()
+ {
+ $snsMock = $this->createSnsContextMock();
+ $snsMock->method('createMessage')->willReturn(new SnsMessage());
+ $destination = new SnsQsTopic('');
+
+ $snsProducerStub = $this->prophesize(SnsProducer::class);
+ $snsProducerStub->send($destination, Argument::any())->shouldBeCalledOnce();
+
+ $snsMock->method('createProducer')->willReturn($snsProducerStub->reveal());
+
+ $producer = new SnsQsProducer($snsMock, $this->createSqsContextMock());
+ $producer->send($destination, new SnsQsMessage());
+ }
+
+ public function testShouldSendSnsTopicMessageWithAttributesToSnsProducer()
+ {
+ $snsMock = $this->createSnsContextMock();
+ $snsMock->method('createMessage')->willReturn(new SnsMessage());
+ $destination = new SnsQsTopic('');
+
+ $snsProducerStub = $this->prophesize(SnsProducer::class);
+ $snsProducerStub->send(
+ $destination,
+ Argument::that(function (SnsMessage $snsMessage) {
+ return $snsMessage->getMessageAttributes() === ['foo' => 'bar'];
+ })
+ )->shouldBeCalledOnce();
+
+ $snsMock->method('createProducer')->willReturn($snsProducerStub->reveal());
+
+ $producer = new SnsQsProducer($snsMock, $this->createSqsContextMock());
+ $producer->send($destination, new SnsQsMessage('', [], [], ['foo' => 'bar']));
+ }
+
+ public function testShouldSendToSnsTopicMessageWithGroupIdAndDeduplicationId()
+ {
+ $snsMock = $this->createSnsContextMock();
+ $snsMock->method('createMessage')->willReturn(new SnsMessage());
+ $destination = new SnsQsTopic('');
+
+ $snsProducerStub = $this->prophesize(SnsProducer::class);
+ $snsProducerStub->send(
+ $destination,
+ Argument::that(function (SnsMessage $snsMessage) {
+ return 'group-id' === $snsMessage->getMessageGroupId()
+ && 'deduplication-id' === $snsMessage->getMessageDeduplicationId();
+ })
+ )->shouldBeCalledOnce();
+
+ $snsMock->method('createProducer')->willReturn($snsProducerStub->reveal());
+
+ $snsMessage = new SnsQsMessage();
+ $snsMessage->setMessageGroupId('group-id');
+ $snsMessage->setMessageDeduplicationId('deduplication-id');
+
+ $producer = new SnsQsProducer($snsMock, $this->createSqsContextMock());
+ $producer->send($destination, $snsMessage);
+ }
+
+ public function testShouldSendSqsMessageToSqsProducer()
+ {
+ $sqsMock = $this->createSqsContextMock();
+ $sqsMock->method('createMessage')->willReturn(new SqsMessage());
+ $destination = new SnsQsQueue('');
+
+ $sqsProducerStub = $this->prophesize(SqsProducer::class);
+ $sqsProducerStub->send($destination, Argument::any())->shouldBeCalledOnce();
+
+ $sqsMock->method('createProducer')->willReturn($sqsProducerStub->reveal());
+
+ $producer = new SnsQsProducer($this->createSnsContextMock(), $sqsMock);
+ $producer->send($destination, new SnsQsMessage());
+ }
+
+ public function testShouldSendToSqsProducerMessageWithGroupIdAndDeduplicationId()
+ {
+ $sqsMock = $this->createSqsContextMock();
+ $sqsMock->method('createMessage')->willReturn(new SqsMessage());
+ $destination = new SnsQsQueue('');
+
+ $sqsProducerStub = $this->prophesize(SqsProducer::class);
+ $sqsProducerStub->send(
+ $destination,
+ Argument::that(function (SqsMessage $sqsMessage) {
+ return 'group-id' === $sqsMessage->getMessageGroupId()
+ && 'deduplication-id' === $sqsMessage->getMessageDeduplicationId();
+ })
+ )->shouldBeCalledOnce();
+
+ $sqsMock->method('createProducer')->willReturn($sqsProducerStub->reveal());
+
+ $sqsMessage = new SnsQsMessage();
+ $sqsMessage->setMessageGroupId('group-id');
+ $sqsMessage->setMessageDeduplicationId('deduplication-id');
+
+ $producer = new SnsQsProducer($this->createSnsContextMock(), $sqsMock);
+ $producer->send($destination, $sqsMessage);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|SnsContext
+ */
+ private function createSnsContextMock(): SnsContext
+ {
+ return $this->createMock(SnsContext::class);
+ }
+
+ /**
+ * @return \PHPUnit\Framework\MockObject\MockObject|SqsContext
+ */
+ private function createSqsContextMock(): SqsContext
+ {
+ return $this->createMock(SqsContext::class);
+ }
+}
diff --git a/pkg/snsqs/Tests/Spec/SnsQsConnectionFactoryTest.php b/pkg/snsqs/Tests/Spec/SnsQsConnectionFactoryTest.php
new file mode 100644
index 000000000..f00c350da
--- /dev/null
+++ b/pkg/snsqs/Tests/Spec/SnsQsConnectionFactoryTest.php
@@ -0,0 +1,18 @@
+createMock(SnsContext::class);
+ $snsContext->expects($this->once())
+ ->method('setSubscriptionAttributes')
+ ->with($this->equalTo(new SnsSubscribe(
+ $topic,
+ 'queueArn1',
+ 'sqs',
+ false,
+ ['attr1' => 'value1'],
+ )));
+
+ $sqsContext = $this->createMock(SqsContext::class);
+ $sqsContext->expects($this->any())
+ ->method('createConsumer')
+ ->willReturn($this->createMock(SqsConsumer::class));
+ $sqsContext->expects($this->any())
+ ->method('getQueueArn')
+ ->willReturn('queueArn1');
+
+ $context = new SnsQsContext($snsContext, $sqsContext);
+ $context->setSubscriptionAttributes(
+ $topic,
+ new SnsQsQueue('queue1'),
+ ['attr1' => 'value1'],
+ );
+ }
+
+ protected function createContext()
+ {
+ $sqsContext = $this->createMock(SqsContext::class);
+ $sqsContext
+ ->expects($this->any())
+ ->method('createConsumer')
+ ->willReturn($this->createMock(SqsConsumer::class))
+ ;
+
+ return new SnsQsContext(
+ $this->createMock(SnsContext::class),
+ $sqsContext
+ );
+ }
+}
diff --git a/pkg/snsqs/Tests/Spec/SnsQsFactoryTrait.php b/pkg/snsqs/Tests/Spec/SnsQsFactoryTrait.php
new file mode 100644
index 000000000..e314c2667
--- /dev/null
+++ b/pkg/snsqs/Tests/Spec/SnsQsFactoryTrait.php
@@ -0,0 +1,68 @@
+snsQsContext = $this->buildSnsQsContext();
+ }
+
+ protected function createSnsQsQueue(string $queueName): SnsQsQueue
+ {
+ $queueName .= time();
+
+ $this->snsQsQueue = $this->snsQsContext->createQueue($queueName);
+ $this->snsQsContext->declareQueue($this->snsQsQueue);
+
+ if ($this->snsQsTopic) {
+ $this->snsQsContext->bind($this->snsQsTopic, $this->snsQsQueue);
+ }
+
+ return $this->snsQsQueue;
+ }
+
+ protected function createSnsQsTopic(string $topicName): SnsQsTopic
+ {
+ $topicName .= time();
+
+ $this->snsQsTopic = $this->snsQsContext->createTopic($topicName);
+ $this->snsQsContext->declareTopic($this->snsQsTopic);
+
+ return $this->snsQsTopic;
+ }
+
+ protected function cleanUpSnsQs(): void
+ {
+ if ($this->snsQsTopic) {
+ $this->snsQsContext->deleteTopic($this->snsQsTopic);
+ }
+
+ if ($this->snsQsQueue) {
+ $this->snsQsContext->deleteQueue($this->snsQsQueue);
+ }
+ }
+}
diff --git a/pkg/snsqs/Tests/Spec/SnsQsMessageTest.php b/pkg/snsqs/Tests/Spec/SnsQsMessageTest.php
new file mode 100644
index 000000000..a2815cde5
--- /dev/null
+++ b/pkg/snsqs/Tests/Spec/SnsQsMessageTest.php
@@ -0,0 +1,14 @@
+createMock(SnsContext::class),
+ $this->createMock(SqsContext::class)
+ );
+ }
+}
diff --git a/pkg/snsqs/Tests/Spec/SnsQsQueueTest.php b/pkg/snsqs/Tests/Spec/SnsQsQueueTest.php
new file mode 100644
index 000000000..6a6bd4dfd
--- /dev/null
+++ b/pkg/snsqs/Tests/Spec/SnsQsQueueTest.php
@@ -0,0 +1,14 @@
+cleanUpSnsQs();
+ }
+
+ protected function createContext()
+ {
+ return $this->createSnsQsContext();
+ }
+
+ protected function createQueue(Context $context, $queueName)
+ {
+ return $this->createSnsQsQueue($queueName);
+ }
+}
diff --git a/pkg/snsqs/Tests/Spec/SnsQsSendToAndReceiveNoWaitFromQueueTest.php b/pkg/snsqs/Tests/Spec/SnsQsSendToAndReceiveNoWaitFromQueueTest.php
new file mode 100644
index 000000000..652766de4
--- /dev/null
+++ b/pkg/snsqs/Tests/Spec/SnsQsSendToAndReceiveNoWaitFromQueueTest.php
@@ -0,0 +1,35 @@
+cleanUpSnsQs();
+ }
+
+ protected function createContext()
+ {
+ return $this->createSnsQsContext();
+ }
+
+ protected function createQueue(Context $context, $queueName)
+ {
+ return $this->createSnsQsQueue($queueName);
+ }
+}
diff --git a/pkg/snsqs/Tests/Spec/SnsQsSendToTopicAndReceiveFromQueueSpec.php b/pkg/snsqs/Tests/Spec/SnsQsSendToTopicAndReceiveFromQueueSpec.php
new file mode 100644
index 000000000..4a5869d63
--- /dev/null
+++ b/pkg/snsqs/Tests/Spec/SnsQsSendToTopicAndReceiveFromQueueSpec.php
@@ -0,0 +1,40 @@
+cleanUpSnsQs();
+ }
+
+ protected function createContext()
+ {
+ return $this->createSnsQsContext();
+ }
+
+ protected function createTopic(Context $context, $topicName)
+ {
+ return $this->createSnsQsTopic($topicName);
+ }
+
+ protected function createQueue(Context $context, $queueName)
+ {
+ return $this->createSnsQsQueue($queueName);
+ }
+}
diff --git a/pkg/snsqs/Tests/Spec/SnsQsSendToTopicAndReceiveNoWaitFromQueueTest.php b/pkg/snsqs/Tests/Spec/SnsQsSendToTopicAndReceiveNoWaitFromQueueTest.php
new file mode 100644
index 000000000..433fcf3a7
--- /dev/null
+++ b/pkg/snsqs/Tests/Spec/SnsQsSendToTopicAndReceiveNoWaitFromQueueTest.php
@@ -0,0 +1,40 @@
+cleanUpSnsQs();
+ }
+
+ protected function createContext()
+ {
+ return $this->createSnsQsContext();
+ }
+
+ protected function createTopic(Context $context, $topicName)
+ {
+ return $this->createSnsQsTopic($topicName);
+ }
+
+ protected function createQueue(Context $context, $queueName)
+ {
+ return $this->createSnsQsQueue($queueName);
+ }
+}
diff --git a/pkg/snsqs/Tests/Spec/SnsQsTopicTest.php b/pkg/snsqs/Tests/Spec/SnsQsTopicTest.php
new file mode 100644
index 000000000..94a455987
--- /dev/null
+++ b/pkg/snsqs/Tests/Spec/SnsQsTopicTest.php
@@ -0,0 +1,14 @@
+ getenv('SNS_DSN'),
+ 'sqs' => getenv('SQS_DSN'),
+]))->createContext();
+
+$topic = $context->createTopic('topic');
+$queue = $context->createQueue('queue');
+
+$context->declareTopic($topic);
+$context->declareQueue($queue);
+$context->bind($topic, $queue);
+
+$consumer = $context->createConsumer($queue);
+
+while (true) {
+ if ($m = $consumer->receive(20000)) {
+ $consumer->acknowledge($m);
+ echo 'Received message: '.$m->getBody().' '.json_encode($m->getHeaders()).' '.json_encode($m->getProperties()).\PHP_EOL;
+ }
+}
+echo 'Done'."\n";
diff --git a/pkg/snsqs/examples/produce.php b/pkg/snsqs/examples/produce.php
new file mode 100644
index 000000000..53018d769
--- /dev/null
+++ b/pkg/snsqs/examples/produce.php
@@ -0,0 +1,40 @@
+ getenv('SNS_DSN'),
+ 'sqs' => getenv('SQS_DSN'),
+]))->createContext();
+
+$topic = $context->createTopic('topic');
+$queue = $context->createQueue('queue');
+
+$context->declareTopic($topic);
+$context->declareQueue($queue);
+$context->bind($topic, $queue);
+
+$message = $context->createMessage('Hello Bar!', ['key' => 'value'], ['key2' => 'value2']);
+
+while (true) {
+ $context->createProducer()->send($topic, $message);
+ echo 'Sent message: '.$message->getBody().\PHP_EOL;
+ sleep(1);
+}
+
+echo 'Done'."\n";
diff --git a/pkg/snsqs/phpunit.xml.dist b/pkg/snsqs/phpunit.xml.dist
new file mode 100644
index 000000000..9adb0b184
--- /dev/null
+++ b/pkg/snsqs/phpunit.xml.dist
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+ ./Tests
+
+
+
+
+
+ .
+
+ ./vendor
+ ./Tests
+
+
+
+
diff --git a/pkg/sqs/.gitattributes b/pkg/sqs/.gitattributes
new file mode 100644
index 000000000..3fab2dac1
--- /dev/null
+++ b/pkg/sqs/.gitattributes
@@ -0,0 +1,6 @@
+/examples export-ignore
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/sqs/.github/workflows/ci.yml b/pkg/sqs/.github/workflows/ci.yml
new file mode 100644
index 000000000..c91cb39ab
--- /dev/null
+++ b/pkg/sqs/.github/workflows/ci.yml
@@ -0,0 +1,29 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/sqs/.travis.yml b/pkg/sqs/.travis.yml
deleted file mode 100644
index 9ed4fa123..000000000
--- a/pkg/sqs/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-sudo: false
-
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
- - '7.2'
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - composer self-update
- - composer install --prefer-source
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/sqs/README.md b/pkg/sqs/README.md
index f5f7589ed..7f4170bf2 100644
--- a/pkg/sqs/README.md
+++ b/pkg/sqs/README.md
@@ -1,19 +1,28 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Amazon SQS Transport
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/sqs)
+[](https://github.com/php-enqueue/sqs/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/sqs)
[](https://packagist.org/packages/enqueue/sqs)
-
-This is an implementation of Queue Interop specification. It allows you to send and consume message through Amazon SQS library.
+
+This is an implementation of Queue Interop specification. It allows you to send and consume message using [Amazon SQS](https://aws.amazon.com/sqs/) service.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/transport/sqs/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
## License
-It is released under the [MIT License](LICENSE).
\ No newline at end of file
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/sqs/SqsClient.php b/pkg/sqs/SqsClient.php
new file mode 100644
index 000000000..bba2a5760
--- /dev/null
+++ b/pkg/sqs/SqsClient.php
@@ -0,0 +1,153 @@
+inputClient = $inputClient;
+ }
+
+ public function deleteMessage(array $args): Result
+ {
+ return $this->callApi('deleteMessage', $args);
+ }
+
+ public function receiveMessage(array $args): Result
+ {
+ return $this->callApi('receiveMessage', $args);
+ }
+
+ public function changeMessageVisibility(array $args): Result
+ {
+ return $this->callApi('changeMessageVisibility', $args);
+ }
+
+ public function purgeQueue(array $args): Result
+ {
+ return $this->callApi('purgeQueue', $args);
+ }
+
+ public function getQueueUrl(array $args): Result
+ {
+ return $this->callApi('getQueueUrl', $args);
+ }
+
+ public function getQueueAttributes(array $args): Result
+ {
+ return $this->callApi('getQueueAttributes', $args);
+ }
+
+ public function createQueue(array $args): Result
+ {
+ return $this->callApi('createQueue', $args);
+ }
+
+ public function deleteQueue(array $args): Result
+ {
+ return $this->callApi('deleteQueue', $args);
+ }
+
+ public function sendMessage(array $args): Result
+ {
+ return $this->callApi('sendMessage', $args);
+ }
+
+ public function getAWSClient(): AwsSqsClient
+ {
+ $this->resolveClient();
+
+ if ($this->singleClient) {
+ return $this->singleClient;
+ }
+
+ if ($this->multiClient) {
+ $mr = new \ReflectionMethod($this->multiClient, 'getClientFromPool');
+ $mr->setAccessible(true);
+ $singleClient = $mr->invoke($this->multiClient, $this->multiClient->getRegion());
+ $mr->setAccessible(false);
+
+ return $singleClient;
+ }
+
+ throw new \LogicException('The multi or single client must be set');
+ }
+
+ private function callApi(string $name, array $args): Result
+ {
+ $this->resolveClient();
+
+ if ($this->singleClient) {
+ if (false == empty($args['@region'])) {
+ throw new \LogicException('Cannot send message to another region because transport is configured with single aws client');
+ }
+
+ unset($args['@region']);
+
+ return call_user_func([$this->singleClient, $name], $args);
+ }
+
+ if ($this->multiClient) {
+ return call_user_func([$this->multiClient, $name], $args);
+ }
+
+ throw new \LogicException('The multi or single client must be set');
+ }
+
+ private function resolveClient(): void
+ {
+ if ($this->singleClient || $this->multiClient) {
+ return;
+ }
+
+ $client = $this->inputClient;
+ if ($client instanceof MultiRegionClient) {
+ $this->multiClient = $client;
+
+ return;
+ } elseif ($client instanceof AwsSqsClient) {
+ $this->singleClient = $client;
+
+ return;
+ } elseif (is_callable($client)) {
+ $client = call_user_func($client);
+ if ($client instanceof MultiRegionClient) {
+ $this->multiClient = $client;
+
+ return;
+ }
+ if ($client instanceof AwsSqsClient) {
+ $this->singleClient = $client;
+
+ return;
+ }
+ }
+
+ throw new \LogicException(sprintf('The input client must be an instance of "%s" or "%s" or a callable that returns one of those. Got "%s"', AwsSqsClient::class, MultiRegionClient::class, is_object($client) ? $client::class : gettype($client)));
+ }
+}
diff --git a/pkg/sqs/SqsConnectionFactory.php b/pkg/sqs/SqsConnectionFactory.php
index 50dad89c2..71e73b705 100644
--- a/pkg/sqs/SqsConnectionFactory.php
+++ b/pkg/sqs/SqsConnectionFactory.php
@@ -4,7 +4,8 @@
namespace Enqueue\Sqs;
-use Aws\Sqs\SqsClient;
+use Aws\Sdk;
+use Aws\Sqs\SqsClient as AwsSqsClient;
use Enqueue\Dsn\Dsn;
use Interop\Queue\ConnectionFactory;
use Interop\Queue\Context;
@@ -23,14 +24,16 @@ class SqsConnectionFactory implements ConnectionFactory
/**
* $config = [
- * 'key' => null - AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
- * 'secret' => null, - AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
- * 'token' => null, - AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
- * 'region' => null, - (string, required) Region to connect to. See http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of available regions.
- * 'retries' => 3, - (int, default=int(3)) Configures the maximum number of allowed retries for a client (pass 0 to disable retries).
- * 'version' => '2012-11-05', - (string, required) The version of the webservice to utilize
- * 'lazy' => true, - Enable lazy connection (boolean)
- * 'endpoint' => null - (string, default=null) The full URI of the webservice. This is only required when connecting to a custom endpoint e.g. localstack
+ * 'key' => null AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
+ * 'secret' => null, AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
+ * 'token' => null, AWS credentials. If no credentials are provided, the SDK will attempt to load them from the environment.
+ * 'region' => null, (string, required) Region to connect to. See http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of available regions.
+ * 'retries' => 3, (int, default=int(3)) Configures the maximum number of allowed retries for a client (pass 0 to disable retries).
+ * 'version' => '2012-11-05', (string, required) The version of the webservice to utilize
+ * 'lazy' => true, Enable lazy connection (boolean)
+ * 'endpoint' => null, (string, default=null) The full URI of the webservice. This is only required when connecting to a custom endpoint e.g. localstack
+ * 'profile' => null, (string, default=null) The name of an AWS profile to used, if provided the SDK will attempt to read associated credentials from the ~/.aws/credentials file.
+ * 'queue_owner_aws_account_id' The AWS account ID of the account that created the queue.
* ].
*
* or
@@ -38,12 +41,12 @@ class SqsConnectionFactory implements ConnectionFactory
* sqs:
* sqs::?key=aKey&secret=aSecret&token=aToken
*
- * @param array|string|SqsClient|null $config
+ * @param array|string|AwsSqsClient|null $config
*/
public function __construct($config = 'sqs:')
{
- if ($config instanceof SqsClient) {
- $this->client = $config;
+ if ($config instanceof AwsSqsClient) {
+ $this->client = new SqsClient($config);
$this->config = ['lazy' => false] + $this->defaultConfig();
return;
@@ -60,7 +63,7 @@ public function __construct($config = 'sqs:')
unset($config['dsn']);
}
} else {
- throw new \LogicException(sprintf('The config must be either an array of options, a DSN string, null or instance of %s', SqsClient::class));
+ throw new \LogicException(sprintf('The config must be either an array of options, a DSN string, null or instance of %s', AwsSqsClient::class));
}
$this->config = array_replace($this->defaultConfig(), $config);
@@ -71,13 +74,7 @@ public function __construct($config = 'sqs:')
*/
public function createContext(): Context
{
- if ($this->config['lazy']) {
- return new SqsContext(function () {
- return $this->establishConnection();
- });
- }
-
- return new SqsContext($this->establishConnection());
+ return new SqsContext($this->establishConnection(), $this->config);
}
private function establishConnection(): SqsClient
@@ -96,6 +93,10 @@ private function establishConnection(): SqsClient
$config['endpoint'] = $this->config['endpoint'];
}
+ if (isset($this->config['profile'])) {
+ $config['profile'] = $this->config['profile'];
+ }
+
if ($this->config['key'] && $this->config['secret']) {
$config['credentials'] = [
'key' => $this->config['key'],
@@ -107,31 +108,42 @@ private function establishConnection(): SqsClient
}
}
- $this->client = new SqsClient($config);
+ if (isset($this->config['http'])) {
+ $config['http'] = $this->config['http'];
+ }
+
+ $establishConnection = function () use ($config) {
+ return (new Sdk(['Sqs' => $config]))->createMultiRegionSqs();
+ };
+
+ $this->client = $this->config['lazy'] ?
+ new SqsClient($establishConnection) :
+ new SqsClient($establishConnection())
+ ;
return $this->client;
}
private function parseDsn(string $dsn): array
{
- $dsn = new Dsn($dsn);
+ $dsn = Dsn::parseFirst($dsn);
if ('sqs' !== $dsn->getSchemeProtocol()) {
- throw new \LogicException(sprintf(
- 'The given scheme protocol "%s" is not supported. It must be "sqs"',
- $dsn->getSchemeProtocol()
- ));
+ throw new \LogicException(sprintf('The given scheme protocol "%s" is not supported. It must be "sqs"', $dsn->getSchemeProtocol()));
}
return array_filter(array_replace($dsn->getQuery(), [
- 'key' => $dsn->getQueryParameter('key'),
- 'secret' => $dsn->getQueryParameter('secret'),
- 'token' => $dsn->getQueryParameter('token'),
- 'region' => $dsn->getQueryParameter('region'),
- 'retries' => $dsn->getInt('retries'),
- 'version' => $dsn->getQueryParameter('version'),
+ 'key' => $dsn->getString('key'),
+ 'secret' => $dsn->getString('secret'),
+ 'token' => $dsn->getString('token'),
+ 'region' => $dsn->getString('region'),
+ 'retries' => $dsn->getDecimal('retries'),
+ 'version' => $dsn->getString('version'),
'lazy' => $dsn->getBool('lazy'),
- 'endpoint' => $dsn->getQueryParameter('endpoint'),
+ 'endpoint' => $dsn->getString('endpoint'),
+ 'profile' => $dsn->getString('profile'),
+ 'queue_owner_aws_account_id' => $dsn->getString('queue_owner_aws_account_id'),
+ 'http' => $dsn->getArray('http', [])->toArray(),
]), function ($value) { return null !== $value; });
}
@@ -146,6 +158,9 @@ private function defaultConfig(): array
'version' => '2012-11-05',
'lazy' => true,
'endpoint' => null,
+ 'profile' => null,
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
];
}
}
diff --git a/pkg/sqs/SqsConsumer.php b/pkg/sqs/SqsConsumer.php
index 1ee37a99d..860bc648b 100644
--- a/pkg/sqs/SqsConsumer.php
+++ b/pkg/sqs/SqsConsumer.php
@@ -53,7 +53,7 @@ public function getVisibilityTimeout(): ?int
* The duration (in seconds) that the received messages are hidden from subsequent retrieve
* requests after being retrieved by a ReceiveMessage request.
*/
- public function setVisibilityTimeout(int $visibilityTimeout = null): void
+ public function setVisibilityTimeout(?int $visibilityTimeout = null): void
{
$this->visibilityTimeout = $visibilityTimeout;
}
@@ -119,7 +119,8 @@ public function acknowledge(Message $message): void
{
InvalidMessageException::assertMessageInstanceOf($message, SqsMessage::class);
- $this->context->getClient()->deleteMessage([
+ $this->context->getSqsClient()->deleteMessage([
+ '@region' => $this->queue->getRegion(),
'QueueUrl' => $this->context->getQueueUrl($this->queue),
'ReceiptHandle' => $message->getReceiptHandle(),
]);
@@ -132,13 +133,19 @@ public function reject(Message $message, bool $requeue = false): void
{
InvalidMessageException::assertMessageInstanceOf($message, SqsMessage::class);
- $this->context->getClient()->deleteMessage([
- 'QueueUrl' => $this->context->getQueueUrl($this->queue),
- 'ReceiptHandle' => $message->getReceiptHandle(),
- ]);
-
if ($requeue) {
- $this->context->createProducer()->send($this->queue, $message);
+ $this->context->getSqsClient()->changeMessageVisibility([
+ '@region' => $this->queue->getRegion(),
+ 'QueueUrl' => $this->context->getQueueUrl($this->queue),
+ 'ReceiptHandle' => $message->getReceiptHandle(),
+ 'VisibilityTimeout' => $message->getRequeueVisibilityTimeout(),
+ ]);
+ } else {
+ $this->context->getSqsClient()->deleteMessage([
+ '@region' => $this->queue->getRegion(),
+ 'QueueUrl' => $this->context->getQueueUrl($this->queue),
+ 'ReceiptHandle' => $message->getReceiptHandle(),
+ ]);
}
}
@@ -149,6 +156,7 @@ protected function receiveMessage(int $timeoutSeconds): ?SqsMessage
}
$arguments = [
+ '@region' => $this->queue->getRegion(),
'AttributeNames' => ['All'],
'MessageAttributeNames' => ['All'],
'MaxNumberOfMessages' => $this->maxNumberOfMessages,
@@ -160,7 +168,7 @@ protected function receiveMessage(int $timeoutSeconds): ?SqsMessage
$arguments['VisibilityTimeout'] = $this->visibilityTimeout;
}
- $result = $this->context->getClient()->receiveMessage($arguments);
+ $result = $this->context->getSqsClient()->receiveMessage($arguments);
if ($result->hasKey('Messages')) {
$this->messages = $result->get('Messages');
@@ -180,6 +188,10 @@ protected function convertMessage(array $sqsMessage): SqsMessage
$message->setBody($sqsMessage['Body']);
$message->setReceiptHandle($sqsMessage['ReceiptHandle']);
+ if (isset($sqsMessage['Attributes'])) {
+ $message->setAttributes($sqsMessage['Attributes']);
+ }
+
if (isset($sqsMessage['Attributes']['ApproximateReceiveCount'])) {
$message->setRedelivered(((int) $sqsMessage['Attributes']['ApproximateReceiveCount']) > 1);
}
@@ -191,6 +203,8 @@ protected function convertMessage(array $sqsMessage): SqsMessage
$message->setProperties($headers[1]);
}
+ $message->setMessageId($sqsMessage['MessageId']);
+
return $message;
}
}
diff --git a/pkg/sqs/SqsContext.php b/pkg/sqs/SqsContext.php
index cb3a9edfa..65f12ae89 100644
--- a/pkg/sqs/SqsContext.php
+++ b/pkg/sqs/SqsContext.php
@@ -4,7 +4,7 @@
namespace Enqueue\Sqs;
-use Aws\Sqs\SqsClient;
+use Aws\Sqs\SqsClient as AwsSqsClient;
use Interop\Queue\Consumer;
use Interop\Queue\Context;
use Interop\Queue\Destination;
@@ -25,33 +25,27 @@ class SqsContext implements Context
private $client;
/**
- * @var callable
+ * @var array
*/
- private $clientFactory;
+ private $queueUrls;
/**
* @var array
*/
- private $queueUrls;
+ private $queueArns;
/**
- * Callable must return instance of SqsClient once called.
- *
- * @param SqsClient|callable $client
+ * @var array
*/
- public function __construct($client)
- {
- if ($client instanceof SqsClient) {
- $this->client = $client;
- } elseif (is_callable($client)) {
- $this->clientFactory = $client;
- } else {
- throw new \InvalidArgumentException(sprintf(
- 'The $client argument must be either %s or callable that returns %s once called.',
- SqsClient::class,
- SqsClient::class
- ));
- }
+ private $config;
+
+ public function __construct(SqsClient $client, array $config)
+ {
+ $this->client = $client;
+ $this->config = $config;
+
+ $this->queueUrls = [];
+ $this->queueArns = [];
}
/**
@@ -114,7 +108,8 @@ public function purgeQueue(Queue $queue): void
{
InvalidDestinationException::assertDestinationInstanceOf($queue, SqsDestination::class);
- $this->getClient()->purgeQueue([
+ $this->client->purgeQueue([
+ '@region' => $queue->getRegion(),
'QueueUrl' => $this->getQueueUrl($queue),
]);
}
@@ -124,44 +119,77 @@ public function createSubscriptionConsumer(): SubscriptionConsumer
throw SubscriptionConsumerNotSupportedException::providerDoestNotSupportIt();
}
- public function getClient(): SqsClient
+ public function getAwsSqsClient(): AwsSqsClient
{
- if (false == $this->client) {
- $client = call_user_func($this->clientFactory);
- if (false == $client instanceof SqsClient) {
- throw new \LogicException(sprintf(
- 'The factory must return instance of "%s". But it returns %s',
- SqsClient::class,
- is_object($client) ? get_class($client) : gettype($client)
- ));
- }
-
- $this->client = $client;
- }
+ return $this->client->getAWSClient();
+ }
+ public function getSqsClient(): SqsClient
+ {
return $this->client;
}
+ /**
+ * @deprecated use getAwsSqsClient method
+ */
+ public function getClient(): AwsSqsClient
+ {
+ @trigger_error('The method is deprecated since 0.9.2. SqsContext::getAwsSqsClient() method should be used.', \E_USER_DEPRECATED);
+
+ return $this->getAwsSqsClient();
+ }
+
public function getQueueUrl(SqsDestination $destination): string
{
if (isset($this->queueUrls[$destination->getQueueName()])) {
return $this->queueUrls[$destination->getQueueName()];
}
- $result = $this->getClient()->getQueueUrl([
+ $arguments = [
+ '@region' => $destination->getRegion(),
'QueueName' => $destination->getQueueName(),
- ]);
+ ];
+
+ if ($destination->getQueueOwnerAWSAccountId()) {
+ $arguments['QueueOwnerAWSAccountId'] = $destination->getQueueOwnerAWSAccountId();
+ } elseif (false == empty($this->config['queue_owner_aws_account_id'])) {
+ $arguments['QueueOwnerAWSAccountId'] = $this->config['queue_owner_aws_account_id'];
+ }
+
+ $result = $this->client->getQueueUrl($arguments);
if (false == $result->hasKey('QueueUrl')) {
throw new \RuntimeException(sprintf('QueueUrl cannot be resolved. queueName: "%s"', $destination->getQueueName()));
}
- return $this->queueUrls[$destination->getQueueName()] = $result->get('QueueUrl');
+ return $this->queueUrls[$destination->getQueueName()] = (string) $result->get('QueueUrl');
+ }
+
+ public function getQueueArn(SqsDestination $destination): string
+ {
+ if (isset($this->queueArns[$destination->getQueueName()])) {
+ return $this->queueArns[$destination->getQueueName()];
+ }
+
+ $arguments = [
+ '@region' => $destination->getRegion(),
+ 'QueueUrl' => $this->getQueueUrl($destination),
+ 'AttributeNames' => ['QueueArn'],
+ ];
+
+ $result = $this->client->getQueueAttributes($arguments);
+
+ if (false == $arn = $result->search('Attributes.QueueArn')) {
+ throw new \RuntimeException(sprintf('QueueArn cannot be resolved. queueName: "%s"', $destination->getQueueName()));
+ }
+
+ return $this->queueArns[$destination->getQueueName()] = (string) $arn;
}
public function declareQueue(SqsDestination $dest): void
{
- $result = $this->getClient()->createQueue([
+ $result = $this->client->createQueue([
+ '@region' => $dest->getRegion(),
'Attributes' => $dest->getAttributes(),
'QueueName' => $dest->getQueueName(),
]);
@@ -175,7 +203,7 @@ public function declareQueue(SqsDestination $dest): void
public function deleteQueue(SqsDestination $dest): void
{
- $this->getClient()->deleteQueue([
+ $this->client->deleteQueue([
'QueueUrl' => $this->getQueueUrl($dest),
]);
diff --git a/pkg/sqs/SqsDestination.php b/pkg/sqs/SqsDestination.php
index 21fc17828..d77966f15 100644
--- a/pkg/sqs/SqsDestination.php
+++ b/pkg/sqs/SqsDestination.php
@@ -14,11 +14,21 @@ class SqsDestination implements Topic, Queue
*/
private $name;
+ /**
+ * @var string|null
+ */
+ private $region;
+
/**
* @var array
*/
private $attributes;
+ /**
+ * @var string|null
+ */
+ private $queueOwnerAWSAccountId;
+
/**
* The name of the new queue.
* The following limits apply to this name:
@@ -52,7 +62,7 @@ public function getAttributes(): array
* The number of seconds for which the delivery of all messages in the queue is delayed.
* Valid values: An integer from 0 to 900 seconds (15 minutes). The default is 0 (zero).
*/
- public function setDelaySeconds(int $seconds = null): void
+ public function setDelaySeconds(?int $seconds = null): void
{
if (null == $seconds) {
unset($this->attributes['DelaySeconds']);
@@ -66,7 +76,7 @@ public function setDelaySeconds(int $seconds = null): void
* Valid values: An integer from 1,024 bytes (1 KiB) to 262,144 bytes (256 KiB).
* The default is 262,144 (256 KiB).
*/
- public function setMaximumMessageSize(int $bytes = null): void
+ public function setMaximumMessageSize(?int $bytes = null): void
{
if (null == $bytes) {
unset($this->attributes['MaximumMessageSize']);
@@ -80,7 +90,7 @@ public function setMaximumMessageSize(int $bytes = null): void
* Valid values: An integer from 60 seconds (1 minute) to 1,209,600 seconds (14 days).
* The default is 345,600 (4 days).
*/
- public function setMessageRetentionPeriod(int $seconds = null): void
+ public function setMessageRetentionPeriod(?int $seconds = null): void
{
if (null == $seconds) {
unset($this->attributes['MessageRetentionPeriod']);
@@ -93,7 +103,7 @@ public function setMessageRetentionPeriod(int $seconds = null): void
* The queue's policy. A valid AWS policy. For more information about policy structure,
* see http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html.
*/
- public function setPolicy(string $policy = null): void
+ public function setPolicy(?string $policy = null): void
{
if (null == $policy) {
unset($this->attributes['Policy']);
@@ -106,7 +116,7 @@ public function setPolicy(string $policy = null): void
* The number of seconds for which a ReceiveMessage action waits for a message to arrive.
* Valid values: An integer from 0 to 20 (seconds). The default is 0 (zero).
*/
- public function setReceiveMessageWaitTimeSeconds(int $seconds = null): void
+ public function setReceiveMessageWaitTimeSeconds(?int $seconds = null): void
{
if (null == $seconds) {
unset($this->attributes['ReceiveMessageWaitTimeSeconds']);
@@ -135,7 +145,7 @@ public function setRedrivePolicy(int $maxReceiveCount, string $deadLetterTargetA
* The default is 30. For more information about the visibility timeout,
* see http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html.
*/
- public function setVisibilityTimeout(int $seconds = null): void
+ public function setVisibilityTimeout(?int $seconds = null): void
{
if (null == $seconds) {
unset($this->attributes['VisibilityTimeout']);
@@ -187,4 +197,24 @@ public function setContentBasedDeduplication(bool $enable): void
unset($this->attributes['ContentBasedDeduplication']);
}
}
+
+ public function getQueueOwnerAWSAccountId(): ?string
+ {
+ return $this->queueOwnerAWSAccountId;
+ }
+
+ public function setQueueOwnerAWSAccountId(?string $queueOwnerAWSAccountId): void
+ {
+ $this->queueOwnerAWSAccountId = $queueOwnerAWSAccountId;
+ }
+
+ public function setRegion(?string $region = null): void
+ {
+ $this->region = $region;
+ }
+
+ public function getRegion(): ?string
+ {
+ return $this->region;
+ }
}
diff --git a/pkg/sqs/SqsMessage.php b/pkg/sqs/SqsMessage.php
index 1d9d26bec..772c3e217 100644
--- a/pkg/sqs/SqsMessage.php
+++ b/pkg/sqs/SqsMessage.php
@@ -23,6 +23,11 @@ class SqsMessage implements Message
*/
private $headers;
+ /**
+ * @var array
+ */
+ private $attributes;
+
/**
* @var bool
*/
@@ -48,13 +53,20 @@ class SqsMessage implements Message
*/
private $receiptHandle;
+ /**
+ * @var int
+ */
+ private $requeueVisibilityTimeout;
+
public function __construct(string $body = '', array $properties = [], array $headers = [])
{
$this->body = $body;
$this->properties = $properties;
$this->headers = $headers;
+ $this->attributes = [];
$this->redelivered = false;
$this->delaySeconds = 0;
+ $this->requeueVisibilityTimeout = 0;
}
public function setBody(string $body): void
@@ -107,6 +119,21 @@ public function getHeader(string $name, $default = null)
return array_key_exists($name, $this->headers) ? $this->headers[$name] : $default;
}
+ public function setAttributes(array $attributes): void
+ {
+ $this->attributes = $attributes;
+ }
+
+ public function getAttributes(): array
+ {
+ return $this->attributes;
+ }
+
+ public function getAttribute(string $name, $default = null)
+ {
+ return array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default;
+ }
+
public function isRedelivered(): bool
{
return $this->redelivered;
@@ -117,7 +144,7 @@ public function setRedelivered(bool $redelivered): void
$this->redelivered = $redelivered;
}
- public function setReplyTo(string $replyTo = null): void
+ public function setReplyTo(?string $replyTo = null): void
{
$this->setHeader('reply_to', $replyTo);
}
@@ -127,7 +154,7 @@ public function getReplyTo(): ?string
return $this->getHeader('reply_to');
}
- public function setCorrelationId(string $correlationId = null): void
+ public function setCorrelationId(?string $correlationId = null): void
{
$this->setHeader('correlation_id', $correlationId);
}
@@ -137,7 +164,7 @@ public function getCorrelationId(): ?string
return $this->getHeader('correlation_id');
}
- public function setMessageId(string $messageId = null): void
+ public function setMessageId(?string $messageId = null): void
{
$this->setHeader('message_id', $messageId);
}
@@ -154,7 +181,7 @@ public function getTimestamp(): ?int
return null === $value ? null : (int) $value;
}
- public function setTimestamp(int $timestamp = null): void
+ public function setTimestamp(?int $timestamp = null): void
{
$this->setHeader('timestamp', $timestamp);
}
@@ -184,7 +211,7 @@ public function getDelaySeconds(): int
* any messages sent with the same MessageDeduplicationId are accepted successfully but aren't delivered during the 5-minute
* deduplication interval. For more information, see http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing.
*/
- public function setMessageDeduplicationId(string $id = null): void
+ public function setMessageDeduplicationId(?string $id = null): void
{
$this->messageDeduplicationId = $id;
}
@@ -203,7 +230,7 @@ public function getMessageDeduplicationId(): ?string
* for multiple users). In this scenario, multiple readers can process the queue, but the session data
* of each user is processed in a FIFO fashion.
*/
- public function setMessageGroupId(string $id = null): void
+ public function setMessageGroupId(?string $id = null): void
{
$this->messageGroupId = $id;
}
@@ -220,7 +247,7 @@ public function getMessageGroupId(): ?string
* If you receive a message more than once, each time you receive it, you get a different receipt handle.
* You must provide the most recently received receipt handle when you request to delete the message (otherwise, the message might not be deleted).
*/
- public function setReceiptHandle(string $receipt = null): void
+ public function setReceiptHandle(?string $receipt = null): void
{
$this->receiptHandle = $receipt;
}
@@ -229,4 +256,19 @@ public function getReceiptHandle(): ?string
{
return $this->receiptHandle;
}
+
+ /**
+ * The number of seconds before the message can be visible again when requeuing. Valid values: 0 to 43200. Maximum: 12 hours.
+ *
+ * Set requeue visibility timeout
+ */
+ public function setRequeueVisibilityTimeout(int $seconds): void
+ {
+ $this->requeueVisibilityTimeout = $seconds;
+ }
+
+ public function getRequeueVisibilityTimeout(): int
+ {
+ return $this->requeueVisibilityTimeout;
+ }
}
diff --git a/pkg/sqs/SqsProducer.php b/pkg/sqs/SqsProducer.php
index 332bee505..2e43d8370 100644
--- a/pkg/sqs/SqsProducer.php
+++ b/pkg/sqs/SqsProducer.php
@@ -44,6 +44,7 @@ public function send(Destination $destination, Message $message): void
}
$arguments = [
+ '@region' => $destination->getRegion(),
'MessageAttributes' => [
'Headers' => [
'DataType' => 'String',
@@ -55,7 +56,7 @@ public function send(Destination $destination, Message $message): void
];
if (null !== $this->deliveryDelay) {
- $arguments['DelaySeconds'] = (int) $this->deliveryDelay / 1000;
+ $arguments['DelaySeconds'] = (int) ceil($this->deliveryDelay / 1000);
}
if ($message->getDelaySeconds()) {
@@ -70,7 +71,7 @@ public function send(Destination $destination, Message $message): void
$arguments['MessageGroupId'] = $message->getMessageGroupId();
}
- $result = $this->context->getClient()->sendMessage($arguments);
+ $result = $this->context->getSqsClient()->sendMessage($arguments);
if (false == $result->hasKey('MessageId')) {
throw new \RuntimeException('Message was not sent');
@@ -80,7 +81,7 @@ public function send(Destination $destination, Message $message): void
/**
* @return SqsProducer
*/
- public function setDeliveryDelay(int $deliveryDelay = null): Producer
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
{
$this->deliveryDelay = $deliveryDelay;
@@ -95,7 +96,7 @@ public function getDeliveryDelay(): ?int
/**
* @return SqsProducer
*/
- public function setPriority(int $priority = null): Producer
+ public function setPriority(?int $priority = null): Producer
{
if (null === $priority) {
return $this;
@@ -112,7 +113,7 @@ public function getPriority(): ?int
/**
* @return SqsProducer
*/
- public function setTimeToLive(int $timeToLive = null): Producer
+ public function setTimeToLive(?int $timeToLive = null): Producer
{
if (null === $timeToLive) {
return $this;
diff --git a/pkg/sqs/Tests/Functional/SqsCommonUseCasesTest.php b/pkg/sqs/Tests/Functional/SqsCommonUseCasesTest.php
index 5c6f11286..7d06df229 100644
--- a/pkg/sqs/Tests/Functional/SqsCommonUseCasesTest.php
+++ b/pkg/sqs/Tests/Functional/SqsCommonUseCasesTest.php
@@ -27,7 +27,7 @@ class SqsCommonUseCasesTest extends TestCase
*/
private $queueName;
- protected function setUp()
+ protected function setUp(): void
{
parent::setUp();
@@ -39,7 +39,7 @@ protected function setUp()
$this->context->declareQueue($this->queue);
}
- protected function tearDown()
+ protected function tearDown(): void
{
parent::tearDown();
@@ -102,7 +102,8 @@ public function testProduceAndReceiveOneMessageSentDirectlyToQueue()
$this->assertEquals(__METHOD__, $message->getBody());
$this->assertEquals(['FooProperty' => 'FooVal'], $message->getProperties());
- $this->assertEquals(['BarHeader' => 'BarVal'], $message->getHeaders());
+ $this->assertEquals('BarVal', $message->getHeaders()['BarHeader']);
+ $this->assertNotNull($message->getMessageId());
}
public function testProduceAndReceiveOneMessageSentDirectlyToTopic()
diff --git a/pkg/sqs/Tests/Functional/SqsConsumptionUseCasesTest.php b/pkg/sqs/Tests/Functional/SqsConsumptionUseCasesTest.php
index b9c1a2987..9c57dcbdc 100644
--- a/pkg/sqs/Tests/Functional/SqsConsumptionUseCasesTest.php
+++ b/pkg/sqs/Tests/Functional/SqsConsumptionUseCasesTest.php
@@ -18,15 +18,15 @@
class SqsConsumptionUseCasesTest extends TestCase
{
- use SqsExtension;
use RetryTrait;
+ use SqsExtension;
/**
* @var SqsContext
*/
private $context;
- protected function setUp()
+ protected function setUp(): void
{
parent::setUp();
diff --git a/pkg/sqs/Tests/Spec/CreateSqsQueueTrait.php b/pkg/sqs/Tests/Spec/CreateSqsQueueTrait.php
new file mode 100644
index 000000000..3af2a5129
--- /dev/null
+++ b/pkg/sqs/Tests/Spec/CreateSqsQueueTrait.php
@@ -0,0 +1,21 @@
+queue = $context->createQueue($queueName);
+ $context->declareQueue($this->queue);
+
+ return $this->queue;
+ }
+}
diff --git a/pkg/sqs/Tests/Spec/SqsMessageTest.php b/pkg/sqs/Tests/Spec/SqsMessageTest.php
index 9007df099..994fe5be5 100644
--- a/pkg/sqs/Tests/Spec/SqsMessageTest.php
+++ b/pkg/sqs/Tests/Spec/SqsMessageTest.php
@@ -7,9 +7,6 @@
class SqsMessageTest extends MessageSpec
{
- /**
- * {@inheritdoc}
- */
protected function createMessage()
{
return new SqsMessage();
diff --git a/pkg/sqs/Tests/Spec/SqsProducerTest.php b/pkg/sqs/Tests/Spec/SqsProducerTest.php
index c241a2165..f0e5c8b06 100644
--- a/pkg/sqs/Tests/Spec/SqsProducerTest.php
+++ b/pkg/sqs/Tests/Spec/SqsProducerTest.php
@@ -12,9 +12,6 @@ class SqsProducerTest extends ProducerSpec
{
use SqsExtension;
- /**
- * {@inheritdoc}
- */
protected function createProducer()
{
return $this->buildSqsContext()->createProducer();
diff --git a/pkg/sqs/Tests/Spec/SqsSendAndReceiveDelayedMessageFromQueueTest.php b/pkg/sqs/Tests/Spec/SqsSendAndReceiveDelayedMessageFromQueueTest.php
index 2c8f2a21a..40f20d68f 100644
--- a/pkg/sqs/Tests/Spec/SqsSendAndReceiveDelayedMessageFromQueueTest.php
+++ b/pkg/sqs/Tests/Spec/SqsSendAndReceiveDelayedMessageFromQueueTest.php
@@ -11,10 +11,12 @@
/**
* @group functional
+ *
* @retry 5
*/
class SqsSendAndReceiveDelayedMessageFromQueueTest extends SendAndReceiveDelayedMessageFromQueueSpec
{
+ use CreateSqsQueueTrait;
use RetryTrait;
use SqsExtension;
@@ -23,12 +25,7 @@ class SqsSendAndReceiveDelayedMessageFromQueueTest extends SendAndReceiveDelayed
*/
private $context;
- /**
- * @var SqsDestination
- */
- private $queue;
-
- protected function tearDown()
+ protected function tearDown(): void
{
parent::tearDown();
@@ -37,26 +34,13 @@ protected function tearDown()
}
}
- /**
- * {@inheritdoc}
- */
- protected function createContext()
+ protected function createContext(): SqsContext
{
return $this->context = $this->buildSqsContext();
}
- /**
- * {@inheritdoc}
- *
- * @param SqsContext $context
- */
- protected function createQueue(Context $context, $queueName)
+ protected function createQueue(Context $context, $queueName): SqsDestination
{
- $queueName = $queueName.time();
-
- $this->queue = $context->createQueue($queueName);
- $context->declareQueue($this->queue);
-
- return $this->queue;
+ return $this->createSqsQueue($context, $queueName);
}
}
diff --git a/pkg/sqs/Tests/Spec/SqsSendToAndReceiveFromQueueTest.php b/pkg/sqs/Tests/Spec/SqsSendToAndReceiveFromQueueTest.php
index 934dda60e..db698017d 100644
--- a/pkg/sqs/Tests/Spec/SqsSendToAndReceiveFromQueueTest.php
+++ b/pkg/sqs/Tests/Spec/SqsSendToAndReceiveFromQueueTest.php
@@ -4,15 +4,20 @@
use Enqueue\Sqs\SqsContext;
use Enqueue\Sqs\SqsDestination;
+use Enqueue\Test\RetryTrait;
use Enqueue\Test\SqsExtension;
use Interop\Queue\Context;
use Interop\Queue\Spec\SendToAndReceiveFromQueueSpec;
/**
* @group functional
+ *
+ * @retry 5
*/
class SqsSendToAndReceiveFromQueueTest extends SendToAndReceiveFromQueueSpec
{
+ use CreateSqsQueueTrait;
+ use RetryTrait;
use SqsExtension;
/**
@@ -20,12 +25,7 @@ class SqsSendToAndReceiveFromQueueTest extends SendToAndReceiveFromQueueSpec
*/
private $context;
- /**
- * @var SqsDestination
- */
- private $queue;
-
- protected function tearDown()
+ protected function tearDown(): void
{
parent::tearDown();
@@ -34,26 +34,13 @@ protected function tearDown()
}
}
- /**
- * {@inheritdoc}
- */
- protected function createContext()
+ protected function createContext(): SqsContext
{
return $this->context = $this->buildSqsContext();
}
- /**
- * {@inheritdoc}
- *
- * @param SqsContext $context
- */
- protected function createQueue(Context $context, $queueName)
+ protected function createQueue(Context $context, $queueName): SqsDestination
{
- $queueName = $queueName.time();
-
- $this->queue = $context->createQueue($queueName);
- $context->declareQueue($this->queue);
-
- return $this->queue;
+ return $this->createSqsQueue($context, $queueName);
}
}
diff --git a/pkg/sqs/Tests/Spec/SqsSendToAndReceiveFromTopicTest.php b/pkg/sqs/Tests/Spec/SqsSendToAndReceiveFromTopicTest.php
index f21e33903..5cd14468a 100644
--- a/pkg/sqs/Tests/Spec/SqsSendToAndReceiveFromTopicTest.php
+++ b/pkg/sqs/Tests/Spec/SqsSendToAndReceiveFromTopicTest.php
@@ -11,24 +11,21 @@
/**
* @group functional
+ *
* @retry 5
*/
class SqsSendToAndReceiveFromTopicTest extends SendToAndReceiveFromTopicSpec
{
- use SqsExtension;
+ use CreateSqsQueueTrait;
use RetryTrait;
+ use SqsExtension;
/**
* @var SqsContext
*/
private $context;
- /**
- * @var SqsDestination
- */
- private $queue;
-
- protected function tearDown()
+ protected function tearDown(): void
{
parent::tearDown();
@@ -37,26 +34,13 @@ protected function tearDown()
}
}
- /**
- * {@inheritdoc}
- */
- protected function createContext()
+ protected function createContext(): SqsContext
{
return $this->context = $this->buildSqsContext();
}
- /**
- * {@inheritdoc}
- *
- * @param SqsContext $context
- */
- protected function createTopic(Context $context, $topicName)
+ protected function createTopic(Context $context, $queueName): SqsDestination
{
- $topicName = $topicName.time();
-
- $this->queue = $context->createTopic($topicName);
- $context->declareQueue($this->queue);
-
- return $this->queue;
+ return $this->createSqsQueue($context, $queueName);
}
}
diff --git a/pkg/sqs/Tests/Spec/SqsSendToAndReceiveNoWaitFromQueueTest.php b/pkg/sqs/Tests/Spec/SqsSendToAndReceiveNoWaitFromQueueTest.php
index 9301c647b..7e31a25a4 100644
--- a/pkg/sqs/Tests/Spec/SqsSendToAndReceiveNoWaitFromQueueTest.php
+++ b/pkg/sqs/Tests/Spec/SqsSendToAndReceiveNoWaitFromQueueTest.php
@@ -2,23 +2,45 @@
namespace Enqueue\Sqs\Tests\Spec;
+use Enqueue\Sqs\SqsContext;
+use Enqueue\Sqs\SqsDestination;
+use Enqueue\Test\RetryTrait;
+use Enqueue\Test\SqsExtension;
+use Interop\Queue\Context;
use Interop\Queue\Spec\SendToAndReceiveNoWaitFromQueueSpec;
/**
* @group functional
+ *
+ * @retry 5
*/
class SqsSendToAndReceiveNoWaitFromQueueTest extends SendToAndReceiveNoWaitFromQueueSpec
{
- public function test()
- {
- $this->markTestSkipped('The test is fragile. This is how SQS.');
- }
+ use CreateSqsQueueTrait;
+ use RetryTrait;
+ use SqsExtension;
/**
- * {@inheritdoc}
+ * @var SqsContext
*/
- protected function createContext()
+ private $context;
+
+ protected function tearDown(): void
+ {
+ parent::tearDown();
+
+ if ($this->context && $this->queue) {
+ $this->context->deleteQueue($this->queue);
+ }
+ }
+
+ protected function createContext(): SqsContext
+ {
+ return $this->context = $this->buildSqsContext();
+ }
+
+ protected function createQueue(Context $context, $queueName): SqsDestination
{
- throw new \LogicException('Should not be ever called');
+ return $this->createSqsQueue($context, $queueName);
}
}
diff --git a/pkg/sqs/Tests/Spec/SqsSendToAndReceiveNoWaitFromTopicTest.php b/pkg/sqs/Tests/Spec/SqsSendToAndReceiveNoWaitFromTopicTest.php
index 3d9149b05..34f2e75dd 100644
--- a/pkg/sqs/Tests/Spec/SqsSendToAndReceiveNoWaitFromTopicTest.php
+++ b/pkg/sqs/Tests/Spec/SqsSendToAndReceiveNoWaitFromTopicTest.php
@@ -2,23 +2,45 @@
namespace Enqueue\Sqs\Tests\Spec;
+use Enqueue\Sqs\SqsContext;
+use Enqueue\Sqs\SqsDestination;
+use Enqueue\Test\RetryTrait;
+use Enqueue\Test\SqsExtension;
+use Interop\Queue\Context;
use Interop\Queue\Spec\SendToAndReceiveNoWaitFromTopicSpec;
/**
* @group functional
+ *
+ * @retry 5
*/
class SqsSendToAndReceiveNoWaitFromTopicTest extends SendToAndReceiveNoWaitFromTopicSpec
{
- public function test()
- {
- $this->markTestSkipped('The test is fragile. This is how SQS.');
- }
+ use CreateSqsQueueTrait;
+ use RetryTrait;
+ use SqsExtension;
/**
- * {@inheritdoc}
+ * @var SqsContext
*/
- protected function createContext()
+ private $context;
+
+ protected function tearDown(): void
+ {
+ parent::tearDown();
+
+ if ($this->context && $this->queue) {
+ $this->context->deleteQueue($this->queue);
+ }
+ }
+
+ protected function createContext(): SqsContext
+ {
+ return $this->context = $this->buildSqsContext();
+ }
+
+ protected function createTopic(Context $context, $queueName): SqsDestination
{
- throw new \LogicException('Should not be ever called');
+ return $this->createSqsQueue($context, $queueName);
}
}
diff --git a/pkg/sqs/Tests/Spec/SqsSendToTopicAndReceiveFromQueueTest.php b/pkg/sqs/Tests/Spec/SqsSendToTopicAndReceiveFromQueueTest.php
index a9db45362..b8e60aee9 100644
--- a/pkg/sqs/Tests/Spec/SqsSendToTopicAndReceiveFromQueueTest.php
+++ b/pkg/sqs/Tests/Spec/SqsSendToTopicAndReceiveFromQueueTest.php
@@ -2,23 +2,50 @@
namespace Enqueue\Sqs\Tests\Spec;
+use Enqueue\Sqs\SqsContext;
+use Enqueue\Sqs\SqsDestination;
+use Enqueue\Test\RetryTrait;
+use Enqueue\Test\SqsExtension;
+use Interop\Queue\Context;
use Interop\Queue\Spec\SendToTopicAndReceiveFromQueueSpec;
/**
* @group functional
+ *
+ * @retry 5
*/
class SqsSendToTopicAndReceiveFromQueueTest extends SendToTopicAndReceiveFromQueueSpec
{
- public function test()
- {
- $this->markTestSkipped('The SQS does not support it');
- }
+ use CreateSqsQueueTrait;
+ use RetryTrait;
+ use SqsExtension;
/**
- * {@inheritdoc}
+ * @var SqsContext
*/
- protected function createContext()
+ private $context;
+
+ protected function tearDown(): void
+ {
+ parent::tearDown();
+
+ if ($this->context && $this->queue) {
+ $this->context->deleteQueue($this->queue);
+ }
+ }
+
+ protected function createContext(): SqsContext
+ {
+ return $this->context = $this->buildSqsContext();
+ }
+
+ protected function createTopic(Context $context, $queueName): SqsDestination
+ {
+ return $this->createSqsQueue($context, $queueName);
+ }
+
+ protected function createQueue(Context $context, $queueName): SqsDestination
{
- throw new \LogicException('Should not be ever called');
+ return $this->createSqsQueue($context, $queueName);
}
}
diff --git a/pkg/sqs/Tests/Spec/SqsSendToTopicAndReceiveNoWaitFromQueueTest.php b/pkg/sqs/Tests/Spec/SqsSendToTopicAndReceiveNoWaitFromQueueTest.php
index bbb9be63a..e5520e01f 100644
--- a/pkg/sqs/Tests/Spec/SqsSendToTopicAndReceiveNoWaitFromQueueTest.php
+++ b/pkg/sqs/Tests/Spec/SqsSendToTopicAndReceiveNoWaitFromQueueTest.php
@@ -2,23 +2,50 @@
namespace Enqueue\Sqs\Tests\Spec;
+use Enqueue\Sqs\SqsContext;
+use Enqueue\Sqs\SqsDestination;
+use Enqueue\Test\RetryTrait;
+use Enqueue\Test\SqsExtension;
+use Interop\Queue\Context;
use Interop\Queue\Spec\SendToTopicAndReceiveNoWaitFromQueueSpec;
/**
* @group functional
+ *
+ * @retry 5
*/
class SqsSendToTopicAndReceiveNoWaitFromQueueTest extends SendToTopicAndReceiveNoWaitFromQueueSpec
{
- public function test()
- {
- $this->markTestSkipped('The SQS does not support it');
- }
+ use CreateSqsQueueTrait;
+ use RetryTrait;
+ use SqsExtension;
/**
- * {@inheritdoc}
+ * @var SqsContext
*/
- protected function createContext()
+ private $context;
+
+ protected function tearDown(): void
+ {
+ parent::tearDown();
+
+ if ($this->context && $this->queue) {
+ $this->context->deleteQueue($this->queue);
+ }
+ }
+
+ protected function createContext(): SqsContext
+ {
+ return $this->context = $this->buildSqsContext();
+ }
+
+ protected function createTopic(Context $context, $queueName): SqsDestination
+ {
+ return $this->createSqsQueue($context, $queueName);
+ }
+
+ protected function createQueue(Context $context, $queueName): SqsDestination
{
- throw new \LogicException('Should not be ever called');
+ return $this->createSqsQueue($context, $queueName);
}
}
diff --git a/pkg/sqs/Tests/SqsClientTest.php b/pkg/sqs/Tests/SqsClientTest.php
new file mode 100644
index 000000000..ff6a966d4
--- /dev/null
+++ b/pkg/sqs/Tests/SqsClientTest.php
@@ -0,0 +1,311 @@
+ [
+ 'key' => '',
+ 'secret' => '',
+ 'region' => 'us-west-2',
+ 'version' => '2012-11-05',
+ 'endpoint' => 'http://localhost',
+ ]]))->createSqs();
+
+ $client = new SqsClient($awsClient);
+
+ $this->assertSame($awsClient, $client->getAWSClient());
+ }
+
+ public function testShouldAllowGetAwsClientIfMultipleClientProvided()
+ {
+ $awsClient = (new Sdk(['Sqs' => [
+ 'key' => '',
+ 'secret' => '',
+ 'region' => 'us-west-2',
+ 'version' => '2012-11-05',
+ 'endpoint' => 'http://localhost',
+ ]]))->createMultiRegionSqs();
+
+ $client = new SqsClient($awsClient);
+
+ $this->assertInstanceOf(AwsSqsClient::class, $client->getAWSClient());
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ * @dataProvider provideApiCallsMultipleClient
+ */
+ public function testApiCall(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $awsClient = $this->getMockBuilder($awsClientClass)
+ ->disableOriginalConstructor()
+ ->setMethods([$method])
+ ->getMock();
+ $awsClient
+ ->expects($this->once())
+ ->method($method)
+ ->with($this->identicalTo($args))
+ ->willReturn(new Result($result));
+
+ $client = new SqsClient($awsClient);
+
+ $actualResult = $client->{$method}($args);
+
+ $this->assertInstanceOf(Result::class, $actualResult);
+ $this->assertSame($result, $actualResult->toArray());
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ * @dataProvider provideApiCallsMultipleClient
+ */
+ public function testLazyApiCall(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $awsClient = $this->getMockBuilder($awsClientClass)
+ ->disableOriginalConstructor()
+ ->setMethods([$method])
+ ->getMock();
+ $awsClient
+ ->expects($this->once())
+ ->method($method)
+ ->with($this->identicalTo($args))
+ ->willReturn(new Result($result));
+
+ $client = new SqsClient(function () use ($awsClient) {
+ return $awsClient;
+ });
+
+ $actualResult = $client->{$method}($args);
+
+ $this->assertInstanceOf(Result::class, $actualResult);
+ $this->assertSame($result, $actualResult->toArray());
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ * @dataProvider provideApiCallsMultipleClient
+ */
+ public function testThrowIfInvalidInputClientApiCall(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $client = new SqsClient(new \stdClass());
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The input client must be an instance of "Aws\Sqs\SqsClient" or "Aws\MultiRegionClient" or a callable that returns one of those. Got "stdClass"');
+ $client->{$method}($args);
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ * @dataProvider provideApiCallsMultipleClient
+ */
+ public function testThrowIfInvalidLazyInputClientApiCall(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $client = new SqsClient(function () { return new \stdClass(); });
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The input client must be an instance of "Aws\Sqs\SqsClient" or "Aws\MultiRegionClient" or a callable that returns one of those. Got "stdClass"');
+ $client->{$method}($args);
+ }
+
+ /**
+ * @dataProvider provideApiCallsMultipleClient
+ */
+ public function testApiCallWithMultiClientAndCustomRegion(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $args['@region'] = 'theRegion';
+
+ $awsClient = $this->getMockBuilder($awsClientClass)
+ ->disableOriginalConstructor()
+ ->setMethods([$method])
+ ->getMock();
+ $awsClient
+ ->expects($this->once())
+ ->method($method)
+ ->with($this->identicalTo($args))
+ ->willReturn(new Result($result));
+
+ $client = new SqsClient($awsClient);
+
+ $actualResult = $client->{$method}($args);
+
+ $this->assertInstanceOf(Result::class, $actualResult);
+ $this->assertSame($result, $actualResult->toArray());
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ */
+ public function testApiCallWithSingleClientAndCustomRegion(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $args['@region'] = 'theRegion';
+
+ $awsClient = $this->getMockBuilder($awsClientClass)
+ ->disableOriginalConstructor()
+ ->setMethods([$method])
+ ->getMock();
+ $awsClient
+ ->expects($this->never())
+ ->method($method)
+ ;
+
+ $client = new SqsClient($awsClient);
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('Cannot send message to another region because transport is configured with single aws client');
+ $client->{$method}($args);
+ }
+
+ /**
+ * @dataProvider provideApiCallsSingleClient
+ */
+ public function testApiCallWithMultiClientAndEmptyCustomRegion(string $method, array $args, array $result, string $awsClientClass)
+ {
+ $expectedArgs = $args;
+ $args['@region'] = '';
+
+ $awsClient = $this->getMockBuilder($awsClientClass)
+ ->disableOriginalConstructor()
+ ->setMethods([$method])
+ ->getMock();
+ $awsClient
+ ->expects($this->once())
+ ->method($method)
+ ->with($this->identicalTo($expectedArgs))
+ ->willReturn(new Result($result));
+
+ $client = new SqsClient($awsClient);
+
+ $actualResult = $client->{$method}($args);
+
+ $this->assertInstanceOf(Result::class, $actualResult);
+ $this->assertSame($result, $actualResult->toArray());
+ }
+
+ public function provideApiCallsSingleClient()
+ {
+ yield [
+ 'deleteMessage',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ AwsSqsClient::class,
+ ];
+
+ yield [
+ 'receiveMessage',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ AwsSqsClient::class,
+ ];
+
+ yield [
+ 'purgeQueue',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ AwsSqsClient::class,
+ ];
+
+ yield [
+ 'getQueueUrl',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ AwsSqsClient::class,
+ ];
+
+ yield [
+ 'getQueueAttributes',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ AwsSqsClient::class,
+ ];
+
+ yield [
+ 'createQueue',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ AwsSqsClient::class,
+ ];
+
+ yield [
+ 'deleteQueue',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ AwsSqsClient::class,
+ ];
+
+ yield [
+ 'sendMessage',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ AwsSqsClient::class,
+ ];
+ }
+
+ public function provideApiCallsMultipleClient()
+ {
+ yield [
+ 'deleteMessage',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ MultiRegionClient::class,
+ ];
+
+ yield [
+ 'receiveMessage',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ MultiRegionClient::class,
+ ];
+
+ yield [
+ 'purgeQueue',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ MultiRegionClient::class,
+ ];
+
+ yield [
+ 'getQueueUrl',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ MultiRegionClient::class,
+ ];
+
+ yield [
+ 'getQueueAttributes',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ MultiRegionClient::class,
+ ];
+
+ yield [
+ 'createQueue',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ MultiRegionClient::class,
+ ];
+
+ yield [
+ 'deleteQueue',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ MultiRegionClient::class,
+ ];
+
+ yield [
+ 'sendMessage',
+ ['fooArg' => 'fooArgVal'],
+ ['bar' => 'barVal'],
+ MultiRegionClient::class,
+ ];
+ }
+}
diff --git a/pkg/sqs/Tests/SqsConnectionFactoryConfigTest.php b/pkg/sqs/Tests/SqsConnectionFactoryConfigTest.php
index f2ad15948..c7a954b0f 100644
--- a/pkg/sqs/Tests/SqsConnectionFactoryConfigTest.php
+++ b/pkg/sqs/Tests/SqsConnectionFactoryConfigTest.php
@@ -4,6 +4,7 @@
use Enqueue\Sqs\SqsConnectionFactory;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use PHPUnit\Framework\TestCase;
/**
@@ -12,6 +13,7 @@
class SqsConnectionFactoryConfigTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testThrowNeitherArrayStringNorNullGivenAsConfig()
{
@@ -39,9 +41,6 @@ public function testThrowIfDsnCouldNotBeParsed()
/**
* @dataProvider provideConfigs
- *
- * @param mixed $config
- * @param mixed $expectedConfig
*/
public function testShouldParseConfigurationAsExpected($config, $expectedConfig)
{
@@ -63,6 +62,9 @@ public static function provideConfigs()
'version' => '2012-11-05',
'lazy' => true,
'endpoint' => null,
+ 'profile' => null,
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
],
];
@@ -77,6 +79,9 @@ public static function provideConfigs()
'version' => '2012-11-05',
'lazy' => true,
'endpoint' => null,
+ 'profile' => null,
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
],
];
@@ -91,6 +96,9 @@ public static function provideConfigs()
'version' => '2012-11-05',
'lazy' => true,
'endpoint' => null,
+ 'profile' => null,
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
],
];
@@ -105,6 +113,9 @@ public static function provideConfigs()
'version' => '2012-11-05',
'lazy' => false,
'endpoint' => null,
+ 'profile' => null,
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
],
];
@@ -119,6 +130,26 @@ public static function provideConfigs()
'version' => '2012-11-05',
'lazy' => false,
'endpoint' => null,
+ 'profile' => null,
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
+ ],
+ ];
+
+ yield [
+ ['dsn' => 'sqs:?profile=staging&lazy=0'],
+ [
+ 'key' => null,
+ 'secret' => null,
+ 'token' => null,
+ 'region' => null,
+ 'retries' => 3,
+ 'version' => '2012-11-05',
+ 'lazy' => false,
+ 'endpoint' => null,
+ 'profile' => 'staging',
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
],
];
@@ -133,6 +164,9 @@ public static function provideConfigs()
'version' => '2012-11-05',
'lazy' => false,
'endpoint' => null,
+ 'profile' => null,
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
],
];
@@ -153,6 +187,48 @@ public static function provideConfigs()
'version' => '2012-11-05',
'lazy' => false,
'endpoint' => 'http://localstack:1111',
+ 'profile' => null,
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
+ ],
+ ];
+
+ yield [
+ [
+ 'profile' => 'staging',
+ ],
+ [
+ 'key' => null,
+ 'secret' => null,
+ 'token' => null,
+ 'region' => null,
+ 'retries' => 3,
+ 'version' => '2012-11-05',
+ 'lazy' => true,
+ 'endpoint' => null,
+ 'profile' => 'staging',
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
+ ],
+ ];
+
+ yield [
+ ['dsn' => 'sqs:?http[timeout]=5&http[connect_timeout]=2'],
+ [
+ 'key' => null,
+ 'secret' => null,
+ 'token' => null,
+ 'region' => null,
+ 'retries' => 3,
+ 'version' => '2012-11-05',
+ 'lazy' => true,
+ 'endpoint' => null,
+ 'profile' => null,
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [
+ 'timeout' => '5',
+ 'connect_timeout' => '2',
+ ],
],
];
}
diff --git a/pkg/sqs/Tests/SqsConnectionFactoryTest.php b/pkg/sqs/Tests/SqsConnectionFactoryTest.php
index c4544c9e0..c327522c5 100644
--- a/pkg/sqs/Tests/SqsConnectionFactoryTest.php
+++ b/pkg/sqs/Tests/SqsConnectionFactoryTest.php
@@ -2,15 +2,19 @@
namespace Enqueue\Sqs\Tests;
-use Aws\Sqs\SqsClient;
+use Aws\Sqs\SqsClient as AwsSqsClient;
+use Enqueue\Sqs\SqsClient;
use Enqueue\Sqs\SqsConnectionFactory;
use Enqueue\Sqs\SqsContext;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use Interop\Queue\ConnectionFactory;
+use PHPUnit\Framework\TestCase;
-class SqsConnectionFactoryTest extends \PHPUnit\Framework\TestCase
+class SqsConnectionFactoryTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testShouldImplementConnectionFactoryInterface()
{
@@ -30,6 +34,9 @@ public function testCouldBeConstructedWithEmptyConfiguration()
'retries' => 3,
'version' => '2012-11-05',
'endpoint' => null,
+ 'profile' => null,
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
], 'config', $factory);
}
@@ -46,19 +53,25 @@ public function testCouldBeConstructedWithCustomConfiguration()
'retries' => 3,
'version' => '2012-11-05',
'endpoint' => null,
+ 'profile' => null,
+ 'queue_owner_aws_account_id' => null,
+ 'http' => [],
], 'config', $factory);
}
public function testCouldBeConstructedWithClient()
{
- $client = $this->createMock(SqsClient::class);
+ $awsClient = $this->createMock(AwsSqsClient::class);
- $factory = new SqsConnectionFactory($client);
+ $factory = new SqsConnectionFactory($awsClient);
$context = $factory->createContext();
$this->assertInstanceOf(SqsContext::class, $context);
- $this->assertAttributeSame($client, 'client', $context);
+
+ $client = $this->readAttribute($context, 'client');
+ $this->assertInstanceOf(SqsClient::class, $client);
+ $this->assertAttributeSame($awsClient, 'inputClient', $client);
}
public function testShouldCreateLazyContext()
@@ -69,7 +82,8 @@ public function testShouldCreateLazyContext()
$this->assertInstanceOf(SqsContext::class, $context);
- $this->assertAttributeEquals(null, 'client', $context);
- $this->assertInternalType('callable', $this->readAttribute($context, 'clientFactory'));
+ $client = $this->readAttribute($context, 'client');
+ $this->assertInstanceOf(SqsClient::class, $client);
+ $this->assertAttributeInstanceOf(\Closure::class, 'inputClient', $client);
}
}
diff --git a/pkg/sqs/Tests/SqsConsumerTest.php b/pkg/sqs/Tests/SqsConsumerTest.php
index c25782682..ef06c6157 100644
--- a/pkg/sqs/Tests/SqsConsumerTest.php
+++ b/pkg/sqs/Tests/SqsConsumerTest.php
@@ -3,7 +3,7 @@
namespace Enqueue\Sqs\Tests;
use Aws\Result;
-use Aws\Sqs\SqsClient;
+use Enqueue\Sqs\SqsClient;
use Enqueue\Sqs\SqsConsumer;
use Enqueue\Sqs\SqsContext;
use Enqueue\Sqs\SqsDestination;
@@ -24,11 +24,6 @@ public function testShouldImplementConsumerInterface()
$this->assertClassImplements(Consumer::class, SqsConsumer::class);
}
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new SqsConsumer($this->createContextMock(), new SqsDestination('queue'));
- }
-
public function testShouldReturnInstanceOfDestination()
{
$destination = new SqsDestination('queue');
@@ -53,13 +48,17 @@ public function testCouldAcknowledgeMessage()
$client
->expects($this->once())
->method('deleteMessage')
- ->with($this->identicalTo(['QueueUrl' => 'theQueueUrl', 'ReceiptHandle' => 'theReceipt']))
+ ->with($this->identicalTo([
+ '@region' => null,
+ 'QueueUrl' => 'theQueueUrl',
+ 'ReceiptHandle' => 'theReceipt',
+ ]))
;
$context = $this->createContextMock();
$context
->expects($this->once())
- ->method('getClient')
+ ->method('getSqsClient')
->willReturn($client)
;
$context
@@ -75,6 +74,41 @@ public function testCouldAcknowledgeMessage()
$consumer->acknowledge($message);
}
+ public function testCouldAcknowledgeMessageWithCustomRegion()
+ {
+ $client = $this->createSqsClientMock();
+ $client
+ ->expects($this->once())
+ ->method('deleteMessage')
+ ->with($this->identicalTo([
+ '@region' => 'theRegion',
+ 'QueueUrl' => 'theQueueUrl',
+ 'ReceiptHandle' => 'theReceipt',
+ ]))
+ ;
+
+ $context = $this->createContextMock();
+ $context
+ ->expects($this->once())
+ ->method('getSqsClient')
+ ->willReturn($client)
+ ;
+ $context
+ ->expects($this->once())
+ ->method('getQueueUrl')
+ ->willReturn('theQueueUrl')
+ ;
+
+ $message = new SqsMessage();
+ $message->setReceiptHandle('theReceipt');
+
+ $destination = new SqsDestination('queue');
+ $destination->setRegion('theRegion');
+
+ $consumer = new SqsConsumer($context, $destination);
+ $consumer->acknowledge($message);
+ }
+
public function testRejectShouldThrowIfInstanceOfMessageIsInvalid()
{
$this->expectException(InvalidMessageException::class);
@@ -90,13 +124,17 @@ public function testShouldRejectMessage()
$client
->expects($this->once())
->method('deleteMessage')
- ->with($this->identicalTo(['QueueUrl' => 'theQueueUrl', 'ReceiptHandle' => 'theReceipt']))
+ ->with($this->identicalTo([
+ '@region' => null,
+ 'QueueUrl' => 'theQueueUrl',
+ 'ReceiptHandle' => 'theReceipt',
+ ]))
;
$context = $this->createContextMock();
$context
->expects($this->once())
- ->method('getClient')
+ ->method('getSqsClient')
->willReturn($client)
;
$context
@@ -116,31 +154,63 @@ public function testShouldRejectMessage()
$consumer->reject($message);
}
- public function testShouldRejectMessageAndRequeue()
+ public function testShouldRejectMessageWithCustomRegion()
{
$client = $this->createSqsClientMock();
$client
->expects($this->once())
->method('deleteMessage')
- ->with($this->identicalTo(['QueueUrl' => 'theQueueUrl', 'ReceiptHandle' => 'theReceipt']))
+ ->with($this->identicalTo([
+ '@region' => 'theRegion',
+ 'QueueUrl' => 'theQueueUrl',
+ 'ReceiptHandle' => 'theReceipt',
+ ]))
+ ;
+
+ $context = $this->createContextMock();
+ $context
+ ->expects($this->once())
+ ->method('getSqsClient')
+ ->willReturn($client)
+ ;
+ $context
+ ->expects($this->once())
+ ->method('getQueueUrl')
+ ->willReturn('theQueueUrl')
+ ;
+ $context
+ ->expects($this->never())
+ ->method('createProducer')
;
$message = new SqsMessage();
$message->setReceiptHandle('theReceipt');
$destination = new SqsDestination('queue');
+ $destination->setRegion('theRegion');
+
+ $consumer = new SqsConsumer($context, $destination);
+ $consumer->reject($message);
+ }
- $producer = $this->createProducerMock();
- $producer
+ public function testShouldRejectMessageAndRequeue()
+ {
+ $client = $this->createSqsClientMock();
+ $client
->expects($this->once())
- ->method('send')
- ->with($this->identicalTo($destination), $this->identicalTo($message))
+ ->method('changeMessageVisibility')
+ ->with($this->identicalTo([
+ '@region' => 'theRegion',
+ 'QueueUrl' => 'theQueueUrl',
+ 'ReceiptHandle' => 'theReceipt',
+ 'VisibilityTimeout' => 0,
+ ]))
;
$context = $this->createContextMock();
$context
->expects($this->once())
- ->method('getClient')
+ ->method('getSqsClient')
->willReturn($client)
;
$context
@@ -148,12 +218,58 @@ public function testShouldRejectMessageAndRequeue()
->method('getQueueUrl')
->willReturn('theQueueUrl')
;
+ $context
+ ->expects($this->never())
+ ->method('createProducer')
+ ;
+
+ $message = new SqsMessage();
+ $message->setReceiptHandle('theReceipt');
+
+ $destination = new SqsDestination('queue');
+ $destination->setRegion('theRegion');
+
+ $consumer = new SqsConsumer($context, $destination);
+ $consumer->reject($message, true);
+ }
+
+ public function testShouldRejectMessageAndRequeueWithVisibilityTimeout()
+ {
+ $client = $this->createSqsClientMock();
+ $client
+ ->expects($this->once())
+ ->method('changeMessageVisibility')
+ ->with($this->identicalTo([
+ '@region' => 'theRegion',
+ 'QueueUrl' => 'theQueueUrl',
+ 'ReceiptHandle' => 'theReceipt',
+ 'VisibilityTimeout' => 30,
+ ]))
+ ;
+
+ $context = $this->createContextMock();
$context
->expects($this->once())
+ ->method('getSqsClient')
+ ->willReturn($client)
+ ;
+ $context
+ ->expects($this->once())
+ ->method('getQueueUrl')
+ ->willReturn('theQueueUrl')
+ ;
+ $context
+ ->expects($this->never())
->method('createProducer')
- ->willReturn($producer)
;
+ $message = new SqsMessage();
+ $message->setReceiptHandle('theReceipt');
+ $message->setRequeueVisibilityTimeout(30);
+
+ $destination = new SqsDestination('queue');
+ $destination->setRegion('theRegion');
+
$consumer = new SqsConsumer($context, $destination);
$consumer->reject($message, true);
}
@@ -161,6 +277,7 @@ public function testShouldRejectMessageAndRequeue()
public function testShouldReceiveMessage()
{
$expectedAttributes = [
+ '@region' => null,
'AttributeNames' => ['All'],
'MessageAttributeNames' => ['All'],
'MaxNumberOfMessages' => 1,
@@ -171,8 +288,12 @@ public function testShouldReceiveMessage()
$expectedSqsMessage = [
'Body' => 'The Body',
'ReceiptHandle' => 'The Receipt',
+ 'MessageId' => 'theMessageId',
'Attributes' => [
- 'ApproximateReceiveCount' => 3,
+ 'SenderId' => 'AROAX5IAWYILCTYIS3OZ5:foo@bar.com',
+ 'ApproximateFirstReceiveTimestamp' => '1560512269481',
+ 'ApproximateReceiveCount' => '3',
+ 'SentTimestamp' => '1560512260079',
],
'MessageAttributes' => [
'Headers' => [
@@ -193,7 +314,7 @@ public function testShouldReceiveMessage()
$context = $this->createContextMock();
$context
->expects($this->once())
- ->method('getClient')
+ ->method('getSqsClient')
->willReturn($client)
;
$context
@@ -212,15 +333,81 @@ public function testShouldReceiveMessage()
$this->assertInstanceOf(SqsMessage::class, $result);
$this->assertEquals('The Body', $result->getBody());
- $this->assertEquals(['hkey' => 'hvalue'], $result->getHeaders());
+ $this->assertEquals(['hkey' => 'hvalue', 'message_id' => 'theMessageId'], $result->getHeaders());
$this->assertEquals(['key' => 'value'], $result->getProperties());
+ $this->assertEquals([
+ 'SenderId' => 'AROAX5IAWYILCTYIS3OZ5:foo@bar.com',
+ 'ApproximateFirstReceiveTimestamp' => '1560512269481',
+ 'ApproximateReceiveCount' => '3',
+ 'SentTimestamp' => '1560512260079',
+ ], $result->getAttributes());
$this->assertTrue($result->isRedelivered());
$this->assertEquals('The Receipt', $result->getReceiptHandle());
+ $this->assertEquals('theMessageId', $result->getMessageId());
+ }
+
+ public function testShouldReceiveMessageWithCustomRegion()
+ {
+ $expectedAttributes = [
+ '@region' => 'theRegion',
+ 'AttributeNames' => ['All'],
+ 'MessageAttributeNames' => ['All'],
+ 'MaxNumberOfMessages' => 1,
+ 'QueueUrl' => 'theQueueUrl',
+ 'WaitTimeSeconds' => 0,
+ ];
+
+ $client = $this->createSqsClientMock();
+ $client
+ ->expects($this->once())
+ ->method('receiveMessage')
+ ->with($this->identicalTo($expectedAttributes))
+ ->willReturn(new Result(['Messages' => [[
+ 'Body' => 'The Body',
+ 'ReceiptHandle' => 'The Receipt',
+ 'MessageId' => 'theMessageId',
+ 'Attributes' => [
+ 'ApproximateReceiveCount' => 3,
+ ],
+ 'MessageAttributes' => [
+ 'Headers' => [
+ 'StringValue' => json_encode([['hkey' => 'hvalue'], ['key' => 'value']]),
+ 'DataType' => 'String',
+ ],
+ ],
+ ]]]))
+ ;
+
+ $context = $this->createContextMock();
+ $context
+ ->expects($this->once())
+ ->method('getSqsClient')
+ ->willReturn($client)
+ ;
+ $context
+ ->expects($this->once())
+ ->method('getQueueUrl')
+ ->willReturn('theQueueUrl')
+ ;
+ $context
+ ->expects($this->once())
+ ->method('createMessage')
+ ->willReturn(new SqsMessage())
+ ;
+
+ $destination = new SqsDestination('queue');
+ $destination->setRegion('theRegion');
+
+ $consumer = new SqsConsumer($context, $destination);
+ $result = $consumer->receiveNoWait();
+
+ $this->assertInstanceOf(SqsMessage::class, $result);
}
public function testShouldReturnNullIfThereIsNoNewMessage()
{
$expectedAttributes = [
+ '@region' => null,
'AttributeNames' => ['All'],
'MessageAttributeNames' => ['All'],
'MaxNumberOfMessages' => 1,
@@ -239,7 +426,7 @@ public function testShouldReturnNullIfThereIsNoNewMessage()
$context = $this->createContextMock();
$context
->expects($this->once())
- ->method('getClient')
+ ->method('getSqsClient')
->willReturn($client)
;
$context
@@ -259,29 +446,25 @@ public function testShouldReturnNullIfThereIsNoNewMessage()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|SqsProducer
+ * @return \PHPUnit\Framework\MockObject\MockObject|SqsProducer
*/
- private function createProducerMock()
+ private function createProducerMock(): SqsProducer
{
return $this->createMock(SqsProducer::class);
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|SqsClient
+ * @return \PHPUnit\Framework\MockObject\MockObject|SqsClient
*/
- private function createSqsClientMock()
+ private function createSqsClientMock(): SqsClient
{
- return $this->getMockBuilder(SqsClient::class)
- ->disableOriginalConstructor()
- ->setMethods(['deleteMessage', 'receiveMessage'])
- ->getMock()
- ;
+ return $this->createMock(SqsClient::class);
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|SqsContext
+ * @return \PHPUnit\Framework\MockObject\MockObject|SqsContext
*/
- private function createContextMock()
+ private function createContextMock(): SqsContext
{
return $this->createMock(SqsContext::class);
}
diff --git a/pkg/sqs/Tests/SqsContextTest.php b/pkg/sqs/Tests/SqsContextTest.php
index f6567d870..5081add41 100644
--- a/pkg/sqs/Tests/SqsContextTest.php
+++ b/pkg/sqs/Tests/SqsContextTest.php
@@ -3,7 +3,7 @@
namespace Enqueue\Sqs\Tests;
use Aws\Result;
-use Aws\Sqs\SqsClient;
+use Enqueue\Sqs\SqsClient;
use Enqueue\Sqs\SqsConsumer;
use Enqueue\Sqs\SqsContext;
use Enqueue\Sqs\SqsDestination;
@@ -14,8 +14,9 @@
use Interop\Queue\Exception\InvalidDestinationException;
use Interop\Queue\Exception\TemporaryQueueNotSupportedException;
use Interop\Queue\Queue;
+use PHPUnit\Framework\TestCase;
-class SqsContextTest extends \PHPUnit\Framework\TestCase
+class SqsContextTest extends TestCase
{
use ClassExtensionTrait;
@@ -24,28 +25,9 @@ public function testShouldImplementContextInterface()
$this->assertClassImplements(Context::class, SqsContext::class);
}
- public function testCouldBeConstructedWithSqsClientAsFirstArgument()
- {
- new SqsContext($this->createSqsClientMock());
- }
-
- public function testCouldBeConstructedWithSqsClientFactoryAsFirstArgument()
- {
- new SqsContext(function () {
- return $this->createSqsClientMock();
- });
- }
-
- public function testThrowIfNeitherSqsClientNorFactoryGiven()
- {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('The $client argument must be either Aws\Sqs\SqsClient or callable that returns Aws\Sqs\SqsClient once called.');
- new SqsContext(new \stdClass());
- }
-
public function testShouldAllowCreateEmptyMessage()
{
- $context = new SqsContext($this->createSqsClientMock());
+ $context = new SqsContext($this->createSqsClientMock(), []);
$message = $context->createMessage();
@@ -58,7 +40,7 @@ public function testShouldAllowCreateEmptyMessage()
public function testShouldAllowCreateCustomMessage()
{
- $context = new SqsContext($this->createSqsClientMock());
+ $context = new SqsContext($this->createSqsClientMock(), []);
$message = $context->createMessage('theBody', ['aProp' => 'aPropVal'], ['aHeader' => 'aHeaderVal']);
@@ -71,7 +53,9 @@ public function testShouldAllowCreateCustomMessage()
public function testShouldCreateQueue()
{
- $context = new SqsContext($this->createSqsClientMock());
+ $context = new SqsContext($this->createSqsClientMock(), [
+ 'queue_owner_aws_account_id' => null,
+ ]);
$queue = $context->createQueue('aQueue');
@@ -81,7 +65,9 @@ public function testShouldCreateQueue()
public function testShouldAllowCreateTopic()
{
- $context = new SqsContext($this->createSqsClientMock());
+ $context = new SqsContext($this->createSqsClientMock(), [
+ 'queue_owner_aws_account_id' => null,
+ ]);
$topic = $context->createTopic('aTopic');
@@ -91,7 +77,7 @@ public function testShouldAllowCreateTopic()
public function testThrowNotImplementedOnCreateTmpQueueCall()
{
- $context = new SqsContext($this->createSqsClientMock());
+ $context = new SqsContext($this->createSqsClientMock(), []);
$this->expectException(TemporaryQueueNotSupportedException::class);
@@ -100,7 +86,7 @@ public function testThrowNotImplementedOnCreateTmpQueueCall()
public function testShouldCreateProducer()
{
- $context = new SqsContext($this->createSqsClientMock());
+ $context = new SqsContext($this->createSqsClientMock(), []);
$producer = $context->createProducer();
@@ -109,7 +95,7 @@ public function testShouldCreateProducer()
public function testShouldThrowIfNotSqsDestinationGivenOnCreateConsumer()
{
- $context = new SqsContext($this->createSqsClientMock());
+ $context = new SqsContext($this->createSqsClientMock(), []);
$this->expectException(InvalidDestinationException::class);
$this->expectExceptionMessage('The destination must be an instance of Enqueue\Sqs\SqsDestination but got Mock_Queue');
@@ -119,7 +105,9 @@ public function testShouldThrowIfNotSqsDestinationGivenOnCreateConsumer()
public function testShouldCreateConsumer()
{
- $context = new SqsContext($this->createSqsClientMock());
+ $context = new SqsContext($this->createSqsClientMock(), [
+ 'queue_owner_aws_account_id' => null,
+ ]);
$queue = $context->createQueue('aQueue');
@@ -134,24 +122,85 @@ public function testShouldAllowDeclareQueue()
$sqsClient
->expects($this->once())
->method('createQueue')
- ->with($this->identicalTo(['Attributes' => [], 'QueueName' => 'aQueueName']))
+ ->with($this->identicalTo([
+ '@region' => null,
+ 'Attributes' => [],
+ 'QueueName' => 'aQueueName',
+ ]))
->willReturn(new Result(['QueueUrl' => 'theQueueUrl']))
;
- $context = new SqsContext($sqsClient);
+ $context = new SqsContext($sqsClient, [
+ 'queue_owner_aws_account_id' => null,
+ ]);
$queue = $context->createQueue('aQueueName');
$context->declareQueue($queue);
}
+ public function testShouldAllowDeclareQueueWithCustomRegion()
+ {
+ $sqsClient = $this->createSqsClientMock();
+ $sqsClient
+ ->expects($this->once())
+ ->method('createQueue')
+ ->with($this->identicalTo([
+ '@region' => 'theRegion',
+ 'Attributes' => [],
+ 'QueueName' => 'aQueueName',
+ ]))
+ ->willReturn(new Result(['QueueUrl' => 'theQueueUrl']))
+ ;
+
+ $context = new SqsContext($sqsClient, [
+ 'queue_owner_aws_account_id' => null,
+ ]);
+
+ $queue = $context->createQueue('aQueueName');
+ $queue->setRegion('theRegion');
+
+ $context->declareQueue($queue);
+ }
+
public function testShouldAllowDeleteQueue()
{
$sqsClient = $this->createSqsClientMock();
$sqsClient
->expects($this->once())
->method('getQueueUrl')
- ->with($this->identicalTo(['QueueName' => 'aQueueName']))
+ ->with($this->identicalTo([
+ '@region' => null,
+ 'QueueName' => 'aQueueName',
+ ]))
+ ->willReturn(new Result(['QueueUrl' => 'theQueueUrl']))
+ ;
+ $sqsClient
+ ->expects($this->once())
+ ->method('deleteQueue')
+ ->with($this->identicalTo(['QueueUrl' => 'theQueueUrl']))
+ ->willReturn(new Result())
+ ;
+
+ $context = new SqsContext($sqsClient, [
+ 'queue_owner_aws_account_id' => null,
+ ]);
+
+ $queue = $context->createQueue('aQueueName');
+
+ $context->deleteQueue($queue);
+ }
+
+ public function testShouldAllowDeleteQueueWithCustomRegion()
+ {
+ $sqsClient = $this->createSqsClientMock();
+ $sqsClient
+ ->expects($this->once())
+ ->method('getQueueUrl')
+ ->with($this->identicalTo([
+ '@region' => 'theRegion',
+ 'QueueName' => 'aQueueName',
+ ]))
->willReturn(new Result(['QueueUrl' => 'theQueueUrl']))
;
$sqsClient
@@ -161,9 +210,12 @@ public function testShouldAllowDeleteQueue()
->willReturn(new Result())
;
- $context = new SqsContext($sqsClient);
+ $context = new SqsContext($sqsClient, [
+ 'queue_owner_aws_account_id' => null,
+ ]);
$queue = $context->createQueue('aQueueName');
+ $queue->setRegion('theRegion');
$context->deleteQueue($queue);
}
@@ -174,19 +226,59 @@ public function testShouldAllowPurgeQueue()
$sqsClient
->expects($this->once())
->method('getQueueUrl')
- ->with($this->identicalTo(['QueueName' => 'aQueueName']))
+ ->with($this->identicalTo([
+ '@region' => null,
+ 'QueueName' => 'aQueueName',
+ ]))
->willReturn(new Result(['QueueUrl' => 'theQueueUrl']))
;
$sqsClient
->expects($this->once())
->method('purgeQueue')
- ->with($this->identicalTo(['QueueUrl' => 'theQueueUrl']))
+ ->with($this->identicalTo([
+ '@region' => null,
+ 'QueueUrl' => 'theQueueUrl',
+ ]))
+ ->willReturn(new Result())
+ ;
+
+ $context = new SqsContext($sqsClient, [
+ 'queue_owner_aws_account_id' => null,
+ ]);
+
+ $queue = $context->createQueue('aQueueName');
+
+ $context->purgeQueue($queue);
+ }
+
+ public function testShouldAllowPurgeQueueWithCustomRegion()
+ {
+ $sqsClient = $this->createSqsClientMock();
+ $sqsClient
+ ->expects($this->once())
+ ->method('getQueueUrl')
+ ->with($this->identicalTo([
+ '@region' => 'theRegion',
+ 'QueueName' => 'aQueueName',
+ ]))
+ ->willReturn(new Result(['QueueUrl' => 'theQueueUrl']))
+ ;
+ $sqsClient
+ ->expects($this->once())
+ ->method('purgeQueue')
+ ->with($this->identicalTo([
+ '@region' => 'theRegion',
+ 'QueueUrl' => 'theQueueUrl',
+ ]))
->willReturn(new Result())
;
- $context = new SqsContext($sqsClient);
+ $context = new SqsContext($sqsClient, [
+ 'queue_owner_aws_account_id' => null,
+ ]);
$queue = $context->createQueue('aQueueName');
+ $queue->setRegion('theRegion');
$context->purgeQueue($queue);
}
@@ -197,26 +289,139 @@ public function testShouldAllowGetQueueUrl()
$sqsClient
->expects($this->once())
->method('getQueueUrl')
- ->with($this->identicalTo(['QueueName' => 'aQueueName']))
+ ->with($this->identicalTo([
+ '@region' => null,
+ 'QueueName' => 'aQueueName',
+ ]))
+ ->willReturn(new Result(['QueueUrl' => 'theQueueUrl']))
+ ;
+
+ $context = new SqsContext($sqsClient, [
+ 'queue_owner_aws_account_id' => null,
+ ]);
+
+ $context->getQueueUrl(new SqsDestination('aQueueName'));
+ }
+
+ public function testShouldAllowGetQueueArn()
+ {
+ $sqsClient = $this->createSqsClientMock();
+ $sqsClient
+ ->expects($this->once())
+ ->method('getQueueUrl')
+ ->with($this->identicalTo([
+ '@region' => 'theRegion',
+ 'QueueName' => 'aQueueName',
+ ]))
+ ->willReturn(new Result(['QueueUrl' => 'theQueueUrl']))
+ ;
+ $sqsClient
+ ->expects($this->once())
+ ->method('getQueueAttributes')
+ ->with($this->identicalTo([
+ '@region' => 'theRegion',
+ 'QueueUrl' => 'theQueueUrl',
+ 'AttributeNames' => ['QueueArn'],
+ ]))
+ ->willReturn(new Result([
+ 'Attributes' => [
+ 'QueueArn' => 'theQueueArn',
+ ],
+ ]))
+ ;
+
+ $context = new SqsContext($sqsClient, []);
+
+ $queue = $context->createQueue('aQueueName');
+ $queue->setRegion('theRegion');
+
+ $this->assertSame('theQueueArn', $context->getQueueArn($queue));
+ }
+
+ public function testShouldAllowGetQueueUrlWithCustomRegion()
+ {
+ $sqsClient = $this->createSqsClientMock();
+ $sqsClient
+ ->expects($this->once())
+ ->method('getQueueUrl')
+ ->with($this->identicalTo([
+ '@region' => 'theRegion',
+ 'QueueName' => 'aQueueName',
+ ]))
->willReturn(new Result(['QueueUrl' => 'theQueueUrl']))
;
- $context = new SqsContext($sqsClient);
+ $context = new SqsContext($sqsClient, [
+ 'queue_owner_aws_account_id' => null,
+ ]);
+
+ $queue = new SqsDestination('aQueueName');
+ $queue->setRegion('theRegion');
+
+ $context->getQueueUrl($queue);
+ }
+
+ public function testShouldAllowGetQueueUrlFromAnotherAWSAccountSetGlobally()
+ {
+ $sqsClient = $this->createSqsClientMock();
+ $sqsClient
+ ->expects($this->once())
+ ->method('getQueueUrl')
+ ->with($this->identicalTo([
+ '@region' => null,
+ 'QueueName' => 'aQueueName',
+ 'QueueOwnerAWSAccountId' => 'anotherAWSAccountID',
+ ]))
+ ->willReturn(new Result(['QueueUrl' => 'theQueueUrl']))
+ ;
+
+ $context = new SqsContext($sqsClient, [
+ 'queue_owner_aws_account_id' => 'anotherAWSAccountID',
+ ]);
$context->getQueueUrl(new SqsDestination('aQueueName'));
}
+ public function testShouldAllowGetQueueUrlFromAnotherAWSAccountSetPerQueue()
+ {
+ $sqsClient = $this->createSqsClientMock();
+ $sqsClient
+ ->expects($this->once())
+ ->method('getQueueUrl')
+ ->with($this->identicalTo([
+ '@region' => null,
+ 'QueueName' => 'aQueueName',
+ 'QueueOwnerAWSAccountId' => 'anotherAWSAccountID',
+ ]))
+ ->willReturn(new Result(['QueueUrl' => 'theQueueUrl']))
+ ;
+
+ $context = new SqsContext($sqsClient, [
+ 'queue_owner_aws_account_id' => null,
+ ]);
+
+ $queue = new SqsDestination('aQueueName');
+ $queue->setQueueOwnerAWSAccountId('anotherAWSAccountID');
+
+ $context->getQueueUrl($queue);
+ }
+
public function testShouldThrowExceptionIfGetQueueUrlResultHasNoQueueUrlProperty()
{
$sqsClient = $this->createSqsClientMock();
$sqsClient
->expects($this->once())
->method('getQueueUrl')
- ->with($this->identicalTo(['QueueName' => 'aQueueName']))
+ ->with($this->identicalTo([
+ '@region' => null,
+ 'QueueName' => 'aQueueName',
+ ]))
->willReturn(new Result([]))
;
- $context = new SqsContext($sqsClient);
+ $context = new SqsContext($sqsClient, [
+ 'queue_owner_aws_account_id' => null,
+ ]);
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('QueueUrl cannot be resolved. queueName: "aQueueName"');
@@ -225,14 +430,10 @@ public function testShouldThrowExceptionIfGetQueueUrlResultHasNoQueueUrlProperty
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|SqsClient
+ * @return \PHPUnit\Framework\MockObject\MockObject|SqsClient
*/
- private function createSqsClientMock()
+ private function createSqsClientMock(): SqsClient
{
- return $this->getMockBuilder(SqsClient::class)
- ->disableOriginalConstructor()
- ->setMethods(['deleteQueue', 'purgeQueue', 'createQueue', 'getQueueUrl'])
- ->getMock()
- ;
+ return $this->createMock(SqsClient::class);
}
}
diff --git a/pkg/sqs/Tests/SqsMessageTest.php b/pkg/sqs/Tests/SqsMessageTest.php
index a6d4e25fb..5da37b531 100644
--- a/pkg/sqs/Tests/SqsMessageTest.php
+++ b/pkg/sqs/Tests/SqsMessageTest.php
@@ -16,6 +16,7 @@ public function testCouldBeConstructedWithoutArguments()
$this->assertSame('', $message->getBody());
$this->assertSame([], $message->getProperties());
$this->assertSame([], $message->getHeaders());
+ $this->assertSame([], $message->getAttributes());
}
public function testCouldBeConstructedWithOptionalArguments()
@@ -90,4 +91,18 @@ public function testShouldAllowGetReceiptHandle()
$this->assertSame('theId', $message->getReceiptHandle());
}
+
+ public function testShouldAllowSettingAndGettingAttributes()
+ {
+ $message = new SqsMessage();
+ $message->setAttributes($attributes = [
+ 'SenderId' => 'AROAX5IAWYILCTYIS3OZ5:foo@bar.com',
+ 'ApproximateFirstReceiveTimestamp' => '1560512269481',
+ 'ApproximateReceiveCount' => '2',
+ 'SentTimestamp' => '1560512260079',
+ ]);
+
+ $this->assertSame($attributes, $message->getAttributes());
+ $this->assertSame($attributes['SenderId'], $message->getAttribute('SenderId'));
+ }
}
diff --git a/pkg/sqs/Tests/SqsProducerTest.php b/pkg/sqs/Tests/SqsProducerTest.php
index fe5e9428b..35cb9850b 100644
--- a/pkg/sqs/Tests/SqsProducerTest.php
+++ b/pkg/sqs/Tests/SqsProducerTest.php
@@ -3,7 +3,7 @@
namespace Enqueue\Sqs\Tests;
use Aws\Result;
-use Aws\Sqs\SqsClient;
+use Enqueue\Sqs\SqsClient;
use Enqueue\Sqs\SqsContext;
use Enqueue\Sqs\SqsDestination;
use Enqueue\Sqs\SqsMessage;
@@ -24,11 +24,6 @@ public function testShouldImplementProducerInterface()
$this->assertClassImplements(Producer::class, SqsProducer::class);
}
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new SqsProducer($this->createSqsContextMock());
- }
-
public function testShouldThrowIfBodyOfInvalidType()
{
$this->expectException(InvalidMessageException::class);
@@ -68,8 +63,8 @@ public function testShouldThrowIfSendMessageFailed()
;
$context
->expects($this->once())
- ->method('getClient')
- ->will($this->returnValue($client))
+ ->method('getSqsClient')
+ ->willReturn($client)
;
$destination = new SqsDestination('queue-name');
@@ -85,6 +80,7 @@ public function testShouldThrowIfSendMessageFailed()
public function testShouldSendMessage()
{
$expectedArguments = [
+ '@region' => null,
'MessageAttributes' => [
'Headers' => [
'DataType' => 'String',
@@ -103,7 +99,7 @@ public function testShouldSendMessage()
->expects($this->once())
->method('sendMessage')
->with($this->identicalTo($expectedArguments))
- ->willReturn(new Result())
+ ->willReturn(new Result(['MessageId' => 'theMessageId']))
;
$context = $this->createSqsContextMock();
@@ -114,8 +110,8 @@ public function testShouldSendMessage()
;
$context
->expects($this->once())
- ->method('getClient')
- ->will($this->returnValue($client))
+ ->method('getSqsClient')
+ ->willReturn($client)
;
$destination = new SqsDestination('queue-name');
@@ -124,8 +120,48 @@ public function testShouldSendMessage()
$message->setMessageDeduplicationId('theDeduplicationId');
$message->setMessageGroupId('groupId');
- $this->expectException(\RuntimeException::class);
- $this->expectExceptionMessage('Message was not sent');
+ $producer = new SqsProducer($context);
+ $producer->send($destination, $message);
+ }
+
+ public function testShouldSendMessageWithCustomRegion()
+ {
+ $expectedArguments = [
+ '@region' => 'theRegion',
+ 'MessageAttributes' => [
+ 'Headers' => [
+ 'DataType' => 'String',
+ 'StringValue' => '[[],[]]',
+ ],
+ ],
+ 'MessageBody' => 'theBody',
+ 'QueueUrl' => 'theQueueUrl',
+ ];
+
+ $client = $this->createSqsClientMock();
+ $client
+ ->expects($this->once())
+ ->method('sendMessage')
+ ->with($this->identicalTo($expectedArguments))
+ ->willReturn(new Result(['MessageId' => 'theMessageId']))
+ ;
+
+ $context = $this->createSqsContextMock();
+ $context
+ ->expects($this->once())
+ ->method('getQueueUrl')
+ ->willReturn('theQueueUrl')
+ ;
+ $context
+ ->expects($this->once())
+ ->method('getSqsClient')
+ ->willReturn($client)
+ ;
+
+ $destination = new SqsDestination('queue-name');
+ $destination->setRegion('theRegion');
+
+ $message = new SqsMessage('theBody');
$producer = new SqsProducer($context);
$producer->send($destination, $message);
@@ -134,6 +170,7 @@ public function testShouldSendMessage()
public function testShouldSendDelayedMessage()
{
$expectedArguments = [
+ '@region' => null,
'MessageAttributes' => [
'Headers' => [
'DataType' => 'String',
@@ -152,7 +189,7 @@ public function testShouldSendDelayedMessage()
->expects($this->once())
->method('sendMessage')
->with($this->identicalTo($expectedArguments))
- ->willReturn(new Result())
+ ->willReturn(new Result(['MessageId' => 'theMessageId']))
;
$context = $this->createSqsContextMock();
@@ -163,8 +200,8 @@ public function testShouldSendDelayedMessage()
;
$context
->expects($this->once())
- ->method('getClient')
- ->will($this->returnValue($client))
+ ->method('getSqsClient')
+ ->willReturn($client)
;
$destination = new SqsDestination('queue-name');
@@ -173,32 +210,24 @@ public function testShouldSendDelayedMessage()
$message->setMessageDeduplicationId('theDeduplicationId');
$message->setMessageGroupId('groupId');
- $this->expectException(\RuntimeException::class);
- $this->expectExceptionMessage('Message was not sent');
-
$producer = new SqsProducer($context);
$producer->setDeliveryDelay(5000);
$producer->send($destination, $message);
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|SqsContext
+ * @return \PHPUnit\Framework\MockObject\MockObject|SqsContext
*/
- private function createSqsContextMock()
+ private function createSqsContextMock(): SqsContext
{
return $this->createMock(SqsContext::class);
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|SqsClient
+ * @return \PHPUnit\Framework\MockObject\MockObject|SqsClient
*/
- private function createSqsClientMock()
+ private function createSqsClientMock(): SqsClient
{
- return $this
- ->getMockBuilder(SqsClient::class)
- ->disableOriginalConstructor()
- ->setMethods(['sendMessage'])
- ->getMock()
- ;
+ return $this->createMock(SqsClient::class);
}
}
diff --git a/pkg/sqs/composer.json b/pkg/sqs/composer.json
index eac171369..2ddc1b267 100644
--- a/pkg/sqs/composer.json
+++ b/pkg/sqs/composer.json
@@ -6,15 +6,15 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "queue-interop/queue-interop": "0.7.x-dev",
- "enqueue/dsn": "0.9.x-dev",
- "aws/aws-sdk-php": "~3.26"
+ "php": "^8.1",
+ "queue-interop/queue-interop": "^0.8",
+ "enqueue/dsn": "^0.10",
+ "aws/aws-sdk-php": "^3.290"
},
"require-dev": {
- "phpunit/phpunit": "~5.4.0",
- "enqueue/test": "0.9.x-dev",
- "queue-interop/queue-spec": "0.6.x-dev"
+ "phpunit/phpunit": "^9.5",
+ "enqueue/test": "0.10.x-dev",
+ "queue-interop/queue-spec": "^0.6.2"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -32,7 +32,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/sqs/examples/consume.php b/pkg/sqs/examples/consume.php
index 9c5eaa12f..d82274d80 100644
--- a/pkg/sqs/examples/consume.php
+++ b/pkg/sqs/examples/consume.php
@@ -12,7 +12,7 @@
if ($autoload) {
require_once $autoload;
} else {
- throw new \LogicException('Composer autoload was not found');
+ throw new LogicException('Composer autoload was not found');
}
use Enqueue\Sqs\SqsConnectionFactory;
@@ -26,7 +26,7 @@
while (true) {
if ($m = $consumer->receive(20000)) {
$consumer->acknowledge($m);
- echo 'Received message: '.$m->getBody().PHP_EOL;
+ echo 'Received message: '.$m->getBody().\PHP_EOL;
}
}
diff --git a/pkg/sqs/examples/produce.php b/pkg/sqs/examples/produce.php
index ba35c84c1..a9ba3e3b7 100644
--- a/pkg/sqs/examples/produce.php
+++ b/pkg/sqs/examples/produce.php
@@ -12,7 +12,7 @@
if ($autoload) {
require_once $autoload;
} else {
- throw new \LogicException('Composer autoload was not found');
+ throw new LogicException('Composer autoload was not found');
}
use Enqueue\Sqs\SqsConnectionFactory;
@@ -27,7 +27,7 @@
while (true) {
$context->createProducer()->send($queue, $message);
- echo 'Sent message: '.$message->getBody().PHP_EOL;
+ echo 'Sent message: '.$message->getBody().\PHP_EOL;
sleep(1);
}
diff --git a/pkg/sqs/phpunit.xml.dist b/pkg/sqs/phpunit.xml.dist
index 7c026b4e6..8fbb94ebf 100644
--- a/pkg/sqs/phpunit.xml.dist
+++ b/pkg/sqs/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/stomp/.gitattributes b/pkg/stomp/.gitattributes
new file mode 100644
index 000000000..3fab2dac1
--- /dev/null
+++ b/pkg/stomp/.gitattributes
@@ -0,0 +1,6 @@
+/examples export-ignore
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/stomp/.github/workflows/ci.yml b/pkg/stomp/.github/workflows/ci.yml
new file mode 100644
index 000000000..c91cb39ab
--- /dev/null
+++ b/pkg/stomp/.github/workflows/ci.yml
@@ -0,0 +1,29 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+ with:
+ composer-options: "--prefer-source"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/stomp/.travis.yml b/pkg/stomp/.travis.yml
deleted file mode 100644
index 9ed4fa123..000000000
--- a/pkg/stomp/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-sudo: false
-
-git:
- depth: 10
-
-language: php
-
-php:
- - '7.1'
- - '7.2'
-
-cache:
- directories:
- - $HOME/.composer/cache
-
-install:
- - composer self-update
- - composer install --prefer-source
-
-script:
- - vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/stomp/BufferedStompClient.php b/pkg/stomp/BufferedStompClient.php
index 5feb88fae..e2c54d731 100644
--- a/pkg/stomp/BufferedStompClient.php
+++ b/pkg/stomp/BufferedStompClient.php
@@ -103,9 +103,6 @@ public function readMessageFrame(string $subscriptionId, int $timeout): ?Frame
}
}
- /**
- * {@inheritdoc}
- */
public function disconnect($sync = false)
{
parent::disconnect($sync);
diff --git a/pkg/stomp/ExtensionType.php b/pkg/stomp/ExtensionType.php
new file mode 100644
index 000000000..c1c265f68
--- /dev/null
+++ b/pkg/stomp/ExtensionType.php
@@ -0,0 +1,12 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# STOMP Transport
[](https://gitter.im/php-enqueue/Lobby)
-[](https://travis-ci.org/php-enqueue/stomp)
+[](https://github.com/php-enqueue/stomp/actions?query=workflow%3ACI)
[](https://packagist.org/packages/enqueue/stomp)
[](https://packagist.org/packages/enqueue/stomp)
-This is an implementation of Queue Interop specification. It allows you to send and consume message via STOMP protocol.
+This is an implementation of Queue Interop specification. It allows you to send and consume message via STOMP protocol.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/transport/stomp/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
-It is released under the [MIT License](LICENSE).
\ No newline at end of file
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/stomp/StompConnectionFactory.php b/pkg/stomp/StompConnectionFactory.php
index 329d3fa95..da9c6f9bd 100644
--- a/pkg/stomp/StompConnectionFactory.php
+++ b/pkg/stomp/StompConnectionFactory.php
@@ -8,9 +8,17 @@
use Interop\Queue\ConnectionFactory;
use Interop\Queue\Context;
use Stomp\Network\Connection;
+use Stomp\Network\Observer\HeartbeatEmitter;
+use Stomp\Network\Observer\ServerAliveObserver;
class StompConnectionFactory implements ConnectionFactory
{
+ public const SUPPORTED_SCHEMES = [
+ ExtensionType::ACTIVEMQ,
+ ExtensionType::RABBITMQ,
+ ExtensionType::ARTEMIS,
+ ];
+
/**
* @var array
*/
@@ -66,13 +74,14 @@ public function __construct($config = 'stomp:')
*/
public function createContext(): Context
{
- if ($this->config['lazy']) {
- return new StompContext(function () {
- return $this->establishConnection();
- });
- }
+ $stomp = $this->config['lazy']
+ ? function () { return $this->establishConnection(); }
+ : $this->establishConnection();
+
+ $target = $this->config['target'];
+ $detectTransientConnections = (bool) $this->config['detect_transient_connections'];
- return new StompContext($this->establishConnection());
+ return new StompContext($stomp, $target, $detectTransientConnections);
}
private function establishConnection(): BufferedStompClient
@@ -83,11 +92,22 @@ private function establishConnection(): BufferedStompClient
$scheme = (true === $config['ssl_on']) ? 'ssl' : 'tcp';
$uri = $scheme.'://'.$config['host'].':'.$config['port'];
$connection = new Connection($uri, $config['connection_timeout']);
+ $connection->setWriteTimeout($config['write_timeout']);
+ $connection->setReadTimeout($config['read_timeout']);
+
+ if ($config['send_heartbeat']) {
+ $connection->getObservers()->addObserver(new HeartbeatEmitter($connection));
+ }
+
+ if ($config['receive_heartbeat']) {
+ $connection->getObservers()->addObserver(new ServerAliveObserver());
+ }
$this->stomp = new BufferedStompClient($connection, $config['buffer_size']);
$this->stomp->setLogin($config['login'], $config['password']);
$this->stomp->setVhostname($config['vhost']);
$this->stomp->setSync($config['sync']);
+ $this->stomp->setHeartbeat($config['send_heartbeat'], $config['receive_heartbeat']);
$this->stomp->connect();
}
@@ -97,29 +117,44 @@ private function establishConnection(): BufferedStompClient
private function parseDsn(string $dsn): array
{
- $dsn = new Dsn($dsn);
+ $dsn = Dsn::parseFirst($dsn);
if ('stomp' !== $dsn->getSchemeProtocol()) {
- throw new \LogicException(sprintf('The given DSN "%s" is not supported. Must start with "stomp:".', $dsn));
+ throw new \LogicException('The given DSN is not supported. Must start with "stomp:".');
+ }
+
+ $schemeExtension = current($dsn->getSchemeExtensions());
+ if (false === $schemeExtension) {
+ $schemeExtension = ExtensionType::RABBITMQ;
+ }
+
+ if (false === in_array($schemeExtension, self::SUPPORTED_SCHEMES, true)) {
+ throw new \LogicException(sprintf('The given DSN is not supported. The scheme extension "%s" provided is not supported. It must be one of %s.', $schemeExtension, implode(', ', self::SUPPORTED_SCHEMES)));
}
return array_filter(array_replace($dsn->getQuery(), [
+ 'target' => $schemeExtension,
'host' => $dsn->getHost(),
'port' => $dsn->getPort(),
'login' => $dsn->getUser(),
'password' => $dsn->getPassword(),
'vhost' => null !== $dsn->getPath() ? ltrim($dsn->getPath(), '/') : null,
- 'buffer_size' => $dsn->getInt('buffer_size'),
- 'connection_timeout' => $dsn->getInt('connection_timeout'),
+ 'buffer_size' => $dsn->getDecimal('buffer_size'),
+ 'connection_timeout' => $dsn->getDecimal('connection_timeout'),
'sync' => $dsn->getBool('sync'),
'lazy' => $dsn->getBool('lazy'),
'ssl_on' => $dsn->getBool('ssl_on'),
+ 'write_timeout' => $dsn->getDecimal('write_timeout'),
+ 'read_timeout' => $dsn->getDecimal('read_timeout'),
+ 'send_heartbeat' => $dsn->getDecimal('send_heartbeat'),
+ 'receive_heartbeat' => $dsn->getDecimal('receive_heartbeat'),
]), function ($value) { return null !== $value; });
}
private function defaultConfig(): array
{
return [
+ 'target' => ExtensionType::RABBITMQ,
'host' => 'localhost',
'port' => 61613,
'login' => 'guest',
@@ -130,6 +165,11 @@ private function defaultConfig(): array
'sync' => false,
'lazy' => true,
'ssl_on' => false,
+ 'write_timeout' => 3,
+ 'read_timeout' => 60,
+ 'send_heartbeat' => 0,
+ 'receive_heartbeat' => 0,
+ 'detect_transient_connections' => false,
];
}
}
diff --git a/pkg/stomp/StompConsumer.php b/pkg/stomp/StompConsumer.php
index 7f792163c..5a80be890 100644
--- a/pkg/stomp/StompConsumer.php
+++ b/pkg/stomp/StompConsumer.php
@@ -5,17 +5,19 @@
namespace Enqueue\Stomp;
use Interop\Queue\Consumer;
+use Interop\Queue\Exception\Exception;
use Interop\Queue\Exception\InvalidMessageException;
use Interop\Queue\Message;
use Interop\Queue\Queue;
use Stomp\Client;
+use Stomp\Exception\ErrorFrameException;
use Stomp\Transport\Frame;
class StompConsumer implements Consumer
{
- const ACK_AUTO = 'auto';
- const ACK_CLIENT = 'client';
- const ACK_CLIENT_INDIVIDUAL = 'client-individual';
+ public const ACK_AUTO = 'auto';
+ public const ACK_CLIENT = 'client';
+ public const ACK_CLIENT_INDIVIDUAL = 'client-individual';
/**
* @var StompDestination
@@ -96,16 +98,20 @@ public function receive(int $timeout = 0): ?Message
{
$this->subscribe();
- if (0 === $timeout) {
- while (true) {
- if ($message = $this->stomp->readMessageFrame($this->subscriptionId, 100)) {
+ try {
+ if (0 === $timeout) {
+ while (true) {
+ if ($message = $this->stomp->readMessageFrame($this->subscriptionId, 100)) {
+ return $this->convertMessage($message);
+ }
+ }
+ } else {
+ if ($message = $this->stomp->readMessageFrame($this->subscriptionId, $timeout)) {
return $this->convertMessage($message);
}
}
- } else {
- if ($message = $this->stomp->readMessageFrame($this->subscriptionId, $timeout)) {
- return $this->convertMessage($message);
- }
+ } catch (ErrorFrameException $e) {
+ throw new Exception($e->getMessage()."\n".$e->getFrame()->getBody(), 0, $e);
}
return null;
@@ -143,10 +149,11 @@ public function reject(Message $message, bool $requeue = false): void
$nackFrame = $this->stomp->getProtocol()->getNackFrame($message->getFrame());
- // rabbitmq STOMP protocol extension
- $nackFrame->addHeaders([
- 'requeue' => $requeue ? 'true' : 'false',
- ]);
+ if (ExtensionType::RABBITMQ === $this->queue->getExtensionType()) {
+ $nackFrame->addHeaders([
+ 'requeue' => $requeue ? 'true' : 'false',
+ ]);
+ }
$this->stomp->sendFrame($nackFrame);
}
@@ -168,13 +175,28 @@ private function subscribe(): void
$this->ackMode
);
- // rabbitmq STOMP protocol extension
$headers = $this->queue->getHeaders();
- $headers['prefetch-count'] = $this->prefetchCount;
- $headers = StompHeadersEncoder::encode($headers);
- foreach ($headers as $key => $value) {
- $frame[$key] = $value;
+ if (ExtensionType::RABBITMQ === $this->queue->getExtensionType()) {
+ $headers['prefetch-count'] = $this->prefetchCount;
+ $headers = StompHeadersEncoder::encode($headers);
+
+ foreach ($headers as $key => $value) {
+ $frame[$key] = $value;
+ }
+ } elseif (ExtensionType::ARTEMIS === $this->queue->getExtensionType()) {
+ $subscriptionName = $this->subscriptionId.'-'.$this->queue->getStompName();
+
+ $artemisHeaders = [];
+
+ $artemisHeaders['client-id'] = true ? $this->subscriptionId : null;
+ $artemisHeaders['durable-subscription-name'] = true ? $subscriptionName : null;
+
+ $artemisHeaders = StompHeadersEncoder::encode(array_filter($artemisHeaders));
+
+ foreach ($artemisHeaders as $key => $value) {
+ $frame[$key] = $value;
+ }
}
$this->stomp->sendFrame($frame);
diff --git a/pkg/stomp/StompContext.php b/pkg/stomp/StompContext.php
index e03b11cb6..1e77f88ee 100644
--- a/pkg/stomp/StompContext.php
+++ b/pkg/stomp/StompContext.php
@@ -23,15 +23,30 @@ class StompContext implements Context
*/
private $stomp;
+ /**
+ * @var string
+ */
+ private $extensionType;
+
+ /**
+ * @var bool
+ */
+ private $useExchangePrefix;
+
/**
* @var callable
*/
private $stompFactory;
+ /**
+ * @var bool
+ */
+ private $transient;
+
/**
* @param BufferedStompClient|callable $stomp
*/
- public function __construct($stomp)
+ public function __construct($stomp, string $extensionType, bool $detectTransientConnections = false)
{
if ($stomp instanceof BufferedStompClient) {
$this->stomp = $stomp;
@@ -40,6 +55,10 @@ public function __construct($stomp)
} else {
throw new \InvalidArgumentException('The stomp argument must be either BufferedStompClient or callable that return BufferedStompClient.');
}
+
+ $this->extensionType = $extensionType;
+ $this->useExchangePrefix = ExtensionType::RABBITMQ === $extensionType;
+ $this->transient = $detectTransientConnections;
}
/**
@@ -55,8 +74,8 @@ public function createMessage(string $body = '', array $properties = [], array $
*/
public function createQueue(string $name): Queue
{
- if (0 !== strpos($name, '/')) {
- $destination = new StompDestination();
+ if (!str_starts_with($name, '/')) {
+ $destination = new StompDestination($this->extensionType);
$destination->setType(StompDestination::TYPE_QUEUE);
$destination->setStompName($name);
@@ -82,9 +101,9 @@ public function createTemporaryQueue(): Queue
*/
public function createTopic(string $name): Topic
{
- if (0 !== strpos($name, '/')) {
- $destination = new StompDestination();
- $destination->setType(StompDestination::TYPE_EXCHANGE);
+ if (!str_starts_with($name, '/')) {
+ $destination = new StompDestination($this->extensionType);
+ $destination->setType($this->useExchangePrefix ? StompDestination::TYPE_EXCHANGE : StompDestination::TYPE_TOPIC);
$destination->setStompName($name);
return $destination;
@@ -111,7 +130,7 @@ public function createDestination(string $destination): StompDestination
foreach ($types as $_type) {
$typePrefix = '/'.$_type.'/';
- if (0 === strpos($dest, $typePrefix)) {
+ if (str_starts_with($dest, $typePrefix)) {
$type = $_type;
$dest = substr($dest, strlen($typePrefix));
@@ -143,7 +162,7 @@ public function createDestination(string $destination): StompDestination
$routingKey = $pieces[1];
}
- $destination = new StompDestination();
+ $destination = new StompDestination($this->extensionType);
$destination->setType($type);
$destination->setStompName($name);
$destination->setRoutingKey($routingKey);
@@ -160,6 +179,8 @@ public function createConsumer(Destination $destination): Consumer
{
InvalidDestinationException::assertDestinationInstanceOf($destination, StompDestination::class);
+ $this->transient = false;
+
return new StompConsumer($this->getStomp(), $destination);
}
@@ -168,6 +189,10 @@ public function createConsumer(Destination $destination): Consumer
*/
public function createProducer(): Producer
{
+ if ($this->transient && $this->stomp) {
+ $this->stomp->disconnect();
+ }
+
return new StompProducer($this->getStomp());
}
@@ -189,17 +214,20 @@ public function purgeQueue(Queue $queue): void
public function getStomp(): BufferedStompClient
{
if (false == $this->stomp) {
- $stomp = call_user_func($this->stompFactory);
- if (false == $stomp instanceof BufferedStompClient) {
- throw new \LogicException(sprintf(
- 'The factory must return instance of BufferedStompClient. It returns %s',
- is_object($stomp) ? get_class($stomp) : gettype($stomp)
- ));
- }
-
- $this->stomp = $stomp;
+ $this->stomp = $this->createStomp();
}
return $this->stomp;
}
+
+ private function createStomp(): BufferedStompClient
+ {
+ $stomp = call_user_func($this->stompFactory);
+
+ if (false == $stomp instanceof BufferedStompClient) {
+ throw new \LogicException(sprintf('The factory must return instance of BufferedStompClient. It returns %s', is_object($stomp) ? $stomp::class : gettype($stomp)));
+ }
+
+ return $stomp;
+ }
}
diff --git a/pkg/stomp/StompDestination.php b/pkg/stomp/StompDestination.php
index b54dde0da..3364968c4 100644
--- a/pkg/stomp/StompDestination.php
+++ b/pkg/stomp/StompDestination.php
@@ -9,16 +9,16 @@
class StompDestination implements Topic, Queue
{
- const TYPE_TOPIC = 'topic';
- const TYPE_EXCHANGE = 'exchange';
- const TYPE_QUEUE = 'queue';
- const TYPE_AMQ_QUEUE = 'amq/queue';
- const TYPE_TEMP_QUEUE = 'temp-queue';
- const TYPE_REPLY_QUEUE = 'reply-queue';
+ public const TYPE_TOPIC = 'topic';
+ public const TYPE_EXCHANGE = 'exchange';
+ public const TYPE_QUEUE = 'queue';
+ public const TYPE_AMQ_QUEUE = 'amq/queue';
+ public const TYPE_TEMP_QUEUE = 'temp-queue';
+ public const TYPE_REPLY_QUEUE = 'reply-queue';
- const HEADER_DURABLE = 'durable';
- const HEADER_AUTO_DELETE = 'auto-delete';
- const HEADER_EXCLUSIVE = 'exclusive';
+ public const HEADER_DURABLE = 'durable';
+ public const HEADER_AUTO_DELETE = 'auto-delete';
+ public const HEADER_EXCLUSIVE = 'exclusive';
/**
* @var string
@@ -39,14 +39,25 @@ class StompDestination implements Topic, Queue
* @var array
*/
private $headers;
+ /**
+ * @var string
+ */
+ private $extensionType;
- public function __construct()
+ public function __construct(string $extensionType)
{
$this->headers = [
self::HEADER_DURABLE => false,
self::HEADER_AUTO_DELETE => true,
self::HEADER_EXCLUSIVE => false,
];
+
+ $this->extensionType = $extensionType;
+ }
+
+ public function getExtensionType(): string
+ {
+ return $this->extensionType;
}
public function getStompName(): string
@@ -65,6 +76,10 @@ public function getQueueName(): string
throw new \LogicException('Destination name is not set');
}
+ if (ExtensionType::ARTEMIS === $this->extensionType) {
+ return $this->getStompName();
+ }
+
$name = '/'.$this->getType().'/'.$this->getStompName();
if ($this->getRoutingKey()) {
@@ -107,7 +122,7 @@ public function getRoutingKey(): ?string
return $this->routingKey;
}
- public function setRoutingKey(string $routingKey = null): void
+ public function setRoutingKey(?string $routingKey = null): void
{
$this->routingKey = $routingKey;
}
diff --git a/pkg/stomp/StompHeadersEncoder.php b/pkg/stomp/StompHeadersEncoder.php
index 27e637cc3..e3484abf6 100644
--- a/pkg/stomp/StompHeadersEncoder.php
+++ b/pkg/stomp/StompHeadersEncoder.php
@@ -6,13 +6,13 @@
class StompHeadersEncoder
{
- const PROPERTY_PREFIX = '_property_';
- const TYPE_PREFIX = '_type_';
- const TYPE_STRING = 's';
- const TYPE_INT = 'i';
- const TYPE_FLOAT = 'f';
- const TYPE_BOOL = 'b';
- const TYPE_NULL = 'n';
+ public const PROPERTY_PREFIX = '_property_';
+ public const TYPE_PREFIX = '_type_';
+ public const TYPE_STRING = 's';
+ public const TYPE_INT = 'i';
+ public const TYPE_FLOAT = 'f';
+ public const TYPE_BOOL = 'b';
+ public const TYPE_NULL = 'n';
public static function encode(array $headers = [], array $properties = []): array
{
@@ -36,7 +36,7 @@ public static function decode(array $headers = []): array
// separate headers/properties
foreach ($headers as $key => $value) {
- if (0 === strpos($key, self::PROPERTY_PREFIX)) {
+ if (str_starts_with($key, self::PROPERTY_PREFIX)) {
$encodedProperties[substr($key, $prefixLength)] = $value;
} else {
$encodedHeaders[$key] = $value;
@@ -94,7 +94,7 @@ private static function doDecode(array $headers = []): array
foreach ($headers as $key => $value) {
// skip type header
- if (0 === strpos($key, self::TYPE_PREFIX)) {
+ if (str_starts_with($key, self::TYPE_PREFIX)) {
continue;
}
diff --git a/pkg/stomp/StompMessage.php b/pkg/stomp/StompMessage.php
index bb563c8cd..7098679b7 100644
--- a/pkg/stomp/StompMessage.php
+++ b/pkg/stomp/StompMessage.php
@@ -120,7 +120,7 @@ public function setRedelivered(bool $redelivered): void
$this->redelivered = $redelivered;
}
- public function setCorrelationId(string $correlationId = null): void
+ public function setCorrelationId(?string $correlationId = null): void
{
$this->setHeader('correlation_id', (string) $correlationId);
}
@@ -130,7 +130,7 @@ public function getCorrelationId(): ?string
return $this->getHeader('correlation_id');
}
- public function setMessageId(string $messageId = null): void
+ public function setMessageId(?string $messageId = null): void
{
$this->setHeader('message_id', (string) $messageId);
}
@@ -147,7 +147,7 @@ public function getTimestamp(): ?int
return null === $value ? null : (int) $value;
}
- public function setTimestamp(int $timestamp = null): void
+ public function setTimestamp(?int $timestamp = null): void
{
$this->setHeader('timestamp', $timestamp);
}
@@ -157,12 +157,12 @@ public function getFrame(): ?Frame
return $this->frame;
}
- public function setFrame(Frame $frame = null): void
+ public function setFrame(?Frame $frame = null): void
{
$this->frame = $frame;
}
- public function setReplyTo(string $replyTo = null): void
+ public function setReplyTo(?string $replyTo = null): void
{
$this->setHeader('reply-to', $replyTo);
}
diff --git a/pkg/stomp/StompProducer.php b/pkg/stomp/StompProducer.php
index 31e03f301..909720973 100644
--- a/pkg/stomp/StompProducer.php
+++ b/pkg/stomp/StompProducer.php
@@ -7,6 +7,7 @@
use Interop\Queue\Destination;
use Interop\Queue\Exception\InvalidDestinationException;
use Interop\Queue\Exception\InvalidMessageException;
+use Interop\Queue\Exception\PriorityNotSupportedException;
use Interop\Queue\Message;
use Interop\Queue\Producer;
use Stomp\Client;
@@ -19,9 +20,6 @@ class StompProducer implements Producer
*/
private $stomp;
- /**
- * @param Client $stomp
- */
public function __construct(Client $stomp)
{
$this->stomp = $stomp;
@@ -44,9 +42,12 @@ public function send(Destination $destination, Message $message): void
$this->stomp->send($destination->getQueueName(), $stompMessage);
}
- public function setDeliveryDelay(int $deliveryDelay = null): Producer
+ /**
+ * @return $this|Producer
+ */
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
{
- if (null === $deliveryDelay) {
+ if (empty($deliveryDelay)) {
return $this;
}
@@ -58,13 +59,18 @@ public function getDeliveryDelay(): ?int
return null;
}
- public function setPriority(int $priority = null): Producer
+ /**
+ * @throws PriorityNotSupportedException
+ *
+ * @return $this|Producer
+ */
+ public function setPriority(?int $priority = null): Producer
{
- if (null === $priority) {
+ if (empty($priority)) {
return $this;
}
- throw new \LogicException('Not implemented');
+ throw PriorityNotSupportedException::providerDoestNotSupportIt();
}
public function getPriority(): ?int
@@ -72,9 +78,12 @@ public function getPriority(): ?int
return null;
}
- public function setTimeToLive(int $timeToLive = null): Producer
+ /**
+ * @return $this|Producer
+ */
+ public function setTimeToLive(?int $timeToLive = null): Producer
{
- if (null === $timeToLive) {
+ if (empty($timeToLive)) {
return $this;
}
diff --git a/pkg/stomp/Tests/BufferedStompClientTest.php b/pkg/stomp/Tests/BufferedStompClientTest.php
index 9e7bfa8df..e4b6226e1 100644
--- a/pkg/stomp/Tests/BufferedStompClientTest.php
+++ b/pkg/stomp/Tests/BufferedStompClientTest.php
@@ -4,6 +4,7 @@
use Enqueue\Stomp\BufferedStompClient;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use Enqueue\Test\WriteAttributeTrait;
use Stomp\Client;
use Stomp\Network\Connection;
@@ -12,6 +13,7 @@
class BufferedStompClientTest extends \PHPUnit\Framework\TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
use WriteAttributeTrait;
public function testShouldExtendLibStompClient()
@@ -19,11 +21,6 @@ public function testShouldExtendLibStompClient()
$this->assertClassExtends(Client::class, BufferedStompClient::class);
}
- public function testCouldBeConstructedWithRequiredArguments()
- {
- new BufferedStompClient('tcp://localhost:12345');
- }
-
public function testCouldGetBufferSizeValue()
{
$client = new BufferedStompClient('tcp://localhost:12345', 12345);
@@ -179,7 +176,7 @@ public function testShouldAddFirstFrameToBufferIfSubscriptionNotEqualAndReturnSe
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Connection
+ * @return \PHPUnit\Framework\MockObject\MockObject|Connection
*/
private function createStompConnectionMock()
{
diff --git a/pkg/stomp/Tests/Functional/StompCommonUseCasesTest.php b/pkg/stomp/Tests/Functional/StompCommonUseCasesTest.php
index 42250ed96..e3f09737a 100644
--- a/pkg/stomp/Tests/Functional/StompCommonUseCasesTest.php
+++ b/pkg/stomp/Tests/Functional/StompCommonUseCasesTest.php
@@ -12,22 +12,22 @@
*/
class StompCommonUseCasesTest extends \PHPUnit\Framework\TestCase
{
- use RabbitmqStompExtension;
use RabbitManagementExtensionTrait;
+ use RabbitmqStompExtension;
/**
* @var StompContext
*/
private $stompContext;
- public function setUp()
+ protected function setUp(): void
{
$this->stompContext = $this->buildStompContext();
$this->removeQueue('stomp.test');
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->stompContext->close();
}
diff --git a/pkg/stomp/Tests/Functional/StompConnectionFactoryTest.php b/pkg/stomp/Tests/Functional/StompConnectionFactoryTest.php
new file mode 100644
index 000000000..6d4223616
--- /dev/null
+++ b/pkg/stomp/Tests/Functional/StompConnectionFactoryTest.php
@@ -0,0 +1,51 @@
+getDsn().'?send_heartbeat=2000';
+ $factory = new StompConnectionFactory($dsn);
+ $this->expectException(HeartbeatException::class);
+ $factory->createContext()->getStomp();
+ }
+
+ public function testShouldCreateConnectionWithSendHeartbeat()
+ {
+ $dsn = $this->getDsn().'?send_heartbeat=2000&read_timeout=1';
+ $factory = new StompConnectionFactory($dsn);
+ $context = $factory->createContext();
+
+ $observers = $context->getStomp()->getConnection()->getObservers()->getObservers();
+ $this->assertAttributeEquals([2000, 0], 'heartbeat', $context->getStomp());
+ $this->assertCount(1, $observers);
+ $this->assertInstanceOf(HeartbeatEmitter::class, $observers[0]);
+ }
+
+ public function testShouldCreateConnectionWithReceiveHeartbeat()
+ {
+ $dsn = $this->getDsn().'?receive_heartbeat=2000';
+ $factory = new StompConnectionFactory($dsn);
+ $context = $factory->createContext();
+
+ $observers = $context->getStomp()->getConnection()->getObservers()->getObservers();
+ $this->assertAttributeEquals([0, 2000], 'heartbeat', $context->getStomp());
+ $this->assertCount(1, $observers);
+ $this->assertInstanceOf(ServerAliveObserver::class, $observers[0]);
+ }
+}
diff --git a/pkg/stomp/Tests/Functional/StompConsumptionUseCasesTest.php b/pkg/stomp/Tests/Functional/StompConsumptionUseCasesTest.php
index 3ab8498ab..2025380fd 100644
--- a/pkg/stomp/Tests/Functional/StompConsumptionUseCasesTest.php
+++ b/pkg/stomp/Tests/Functional/StompConsumptionUseCasesTest.php
@@ -20,22 +20,22 @@
*/
class StompConsumptionUseCasesTest extends \PHPUnit\Framework\TestCase
{
- use RabbitmqStompExtension;
use RabbitManagementExtensionTrait;
+ use RabbitmqStompExtension;
/**
* @var StompContext
*/
private $stompContext;
- public function setUp()
+ protected function setUp(): void
{
$this->stompContext = $this->buildStompContext();
$this->removeQueue('stomp.test');
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->stompContext->close();
}
diff --git a/pkg/stomp/Tests/Functional/StompRpcUseCasesTest.php b/pkg/stomp/Tests/Functional/StompRpcUseCasesTest.php
index f054ffdd7..4cbb3af47 100644
--- a/pkg/stomp/Tests/Functional/StompRpcUseCasesTest.php
+++ b/pkg/stomp/Tests/Functional/StompRpcUseCasesTest.php
@@ -14,15 +14,15 @@
*/
class StompRpcUseCasesTest extends \PHPUnit\Framework\TestCase
{
- use RabbitmqStompExtension;
use RabbitManagementExtensionTrait;
+ use RabbitmqStompExtension;
/**
* @var StompContext
*/
private $stompContext;
- public function setUp()
+ protected function setUp(): void
{
$this->stompContext = $this->buildStompContext();
@@ -30,7 +30,7 @@ public function setUp()
$this->removeQueue('stomp.rpc.reply_test');
}
- public function tearDown()
+ protected function tearDown(): void
{
$this->stompContext->close();
}
diff --git a/pkg/stomp/Tests/Spec/StompMessageTest.php b/pkg/stomp/Tests/Spec/StompMessageTest.php
index dd9e733ea..8f6748b63 100644
--- a/pkg/stomp/Tests/Spec/StompMessageTest.php
+++ b/pkg/stomp/Tests/Spec/StompMessageTest.php
@@ -7,9 +7,6 @@
class StompMessageTest extends MessageSpec
{
- /**
- * {@inheritdoc}
- */
protected function createMessage()
{
return new StompMessage();
diff --git a/pkg/stomp/Tests/StompConnectionFactoryConfigTest.php b/pkg/stomp/Tests/StompConnectionFactoryConfigTest.php
index 16a481bb2..d784d4104 100644
--- a/pkg/stomp/Tests/StompConnectionFactoryConfigTest.php
+++ b/pkg/stomp/Tests/StompConnectionFactoryConfigTest.php
@@ -4,6 +4,7 @@
use Enqueue\Stomp\StompConnectionFactory;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use PHPUnit\Framework\TestCase;
/**
@@ -12,6 +13,7 @@
class StompConnectionFactoryConfigTest extends TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testThrowNeitherArrayStringNorNullGivenAsConfig()
{
@@ -24,7 +26,7 @@ public function testThrowNeitherArrayStringNorNullGivenAsConfig()
public function testThrowIfSchemeIsNotStomp()
{
$this->expectException(\LogicException::class);
- $this->expectExceptionMessage('The given DSN "http://example.com" is not supported. Must start with "stomp:".');
+ $this->expectExceptionMessage('The given DSN is not supported. Must start with "stomp:".');
new StompConnectionFactory('http://example.com');
}
@@ -39,9 +41,6 @@ public function testThrowIfDsnCouldNotBeParsed()
/**
* @dataProvider provideConfigs
- *
- * @param mixed $config
- * @param mixed $expectedConfig
*/
public function testShouldParseConfigurationAsExpected($config, $expectedConfig)
{
@@ -55,6 +54,7 @@ public static function provideConfigs()
yield [
null,
[
+ 'target' => 'rabbitmq',
'host' => 'localhost',
'port' => 61613,
'login' => 'guest',
@@ -65,12 +65,18 @@ public static function provideConfigs()
'sync' => false,
'lazy' => true,
'ssl_on' => false,
+ 'write_timeout' => 3,
+ 'read_timeout' => 60,
+ 'send_heartbeat' => 0,
+ 'receive_heartbeat' => 0,
+ 'detect_transient_connections' => false,
],
];
yield [
'stomp:',
[
+ 'target' => 'rabbitmq',
'host' => 'localhost',
'port' => 61613,
'login' => 'guest',
@@ -81,12 +87,18 @@ public static function provideConfigs()
'sync' => false,
'lazy' => true,
'ssl_on' => false,
+ 'write_timeout' => 3,
+ 'read_timeout' => 60,
+ 'send_heartbeat' => 0,
+ 'receive_heartbeat' => 0,
+ 'detect_transient_connections' => false,
],
];
yield [
[],
[
+ 'target' => 'rabbitmq',
'host' => 'localhost',
'port' => 61613,
'login' => 'guest',
@@ -97,12 +109,18 @@ public static function provideConfigs()
'sync' => false,
'lazy' => true,
'ssl_on' => false,
+ 'write_timeout' => 3,
+ 'read_timeout' => 60,
+ 'send_heartbeat' => 0,
+ 'receive_heartbeat' => 0,
+ 'detect_transient_connections' => false,
],
];
yield [
'stomp://localhost:1234?foo=bar&lazy=0&sync=true',
[
+ 'target' => 'rabbitmq',
'host' => 'localhost',
'port' => 1234,
'login' => 'guest',
@@ -114,12 +132,64 @@ public static function provideConfigs()
'lazy' => false,
'foo' => 'bar',
'ssl_on' => false,
+ 'write_timeout' => 3,
+ 'read_timeout' => 60,
+ 'send_heartbeat' => 0,
+ 'receive_heartbeat' => 0,
+ 'detect_transient_connections' => false,
+ ],
+ ];
+
+ yield [
+ 'stomp+activemq://localhost:1234?foo=bar&lazy=0&sync=true',
+ [
+ 'target' => 'activemq',
+ 'host' => 'localhost',
+ 'port' => 1234,
+ 'login' => 'guest',
+ 'password' => 'guest',
+ 'vhost' => '/',
+ 'buffer_size' => 1000,
+ 'connection_timeout' => 1,
+ 'sync' => true,
+ 'lazy' => false,
+ 'foo' => 'bar',
+ 'ssl_on' => false,
+ 'write_timeout' => 3,
+ 'read_timeout' => 60,
+ 'send_heartbeat' => 0,
+ 'receive_heartbeat' => 0,
+ 'detect_transient_connections' => false,
+ ],
+ ];
+
+ yield [
+ 'stomp+rabbitmq://localhost:1234?foo=bar&lazy=0&sync=true',
+ [
+ 'target' => 'rabbitmq',
+ 'host' => 'localhost',
+ 'port' => 1234,
+ 'login' => 'guest',
+ 'password' => 'guest',
+ 'vhost' => '/',
+ 'buffer_size' => 1000,
+ 'connection_timeout' => 1,
+ 'sync' => true,
+ 'lazy' => false,
+ 'foo' => 'bar',
+ 'ssl_on' => false,
+ 'write_timeout' => 3,
+ 'read_timeout' => 60,
+ 'send_heartbeat' => 0,
+ 'receive_heartbeat' => 0,
+ 'detect_transient_connections' => false,
],
];
yield [
['dsn' => 'stomp://localhost:1234/theVhost?foo=bar&lazy=0&sync=true', 'baz' => 'bazVal', 'foo' => 'fooVal'],
[
+ 'target' => 'rabbitmq',
'host' => 'localhost',
'port' => 1234,
'login' => 'guest',
@@ -132,12 +202,18 @@ public static function provideConfigs()
'foo' => 'bar',
'ssl_on' => false,
'baz' => 'bazVal',
+ 'write_timeout' => 3,
+ 'read_timeout' => 60,
+ 'send_heartbeat' => 0,
+ 'receive_heartbeat' => 0,
+ 'detect_transient_connections' => false,
],
];
yield [
['dsn' => 'stomp:///%2f'],
[
+ 'target' => 'rabbitmq',
'host' => 'localhost',
'port' => 61613,
'login' => 'guest',
@@ -148,12 +224,18 @@ public static function provideConfigs()
'sync' => false,
'lazy' => true,
'ssl_on' => false,
+ 'write_timeout' => 3,
+ 'read_timeout' => 60,
+ 'send_heartbeat' => 0,
+ 'receive_heartbeat' => 0,
+ 'detect_transient_connections' => false,
],
];
yield [
['host' => 'localhost', 'port' => 1234, 'foo' => 'bar'],
[
+ 'target' => 'rabbitmq',
'host' => 'localhost',
'port' => 1234,
'login' => 'guest',
@@ -165,6 +247,11 @@ public static function provideConfigs()
'lazy' => true,
'foo' => 'bar',
'ssl_on' => false,
+ 'write_timeout' => 3,
+ 'read_timeout' => 60,
+ 'send_heartbeat' => 0,
+ 'receive_heartbeat' => 0,
+ 'detect_transient_connections' => false,
],
];
}
diff --git a/pkg/stomp/Tests/StompConnectionFactoryTest.php b/pkg/stomp/Tests/StompConnectionFactoryTest.php
index 18a13463f..1f39e3b20 100644
--- a/pkg/stomp/Tests/StompConnectionFactoryTest.php
+++ b/pkg/stomp/Tests/StompConnectionFactoryTest.php
@@ -5,11 +5,13 @@
use Enqueue\Stomp\StompConnectionFactory;
use Enqueue\Stomp\StompContext;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use Interop\Queue\ConnectionFactory;
class StompConnectionFactoryTest extends \PHPUnit\Framework\TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testShouldImplementConnectionFactoryInterface()
{
@@ -25,6 +27,31 @@ public function testShouldCreateLazyContext()
$this->assertInstanceOf(StompContext::class, $context);
$this->assertAttributeEquals(null, 'stomp', $context);
- $this->assertInternalType('callable', $this->readAttribute($context, 'stompFactory'));
+ $this->assertAttributeEquals(true, 'useExchangePrefix', $context);
+ self::assertIsCallable($this->readAttribute($context, 'stompFactory'));
+ }
+
+ public function testShouldCreateRabbitMQContext()
+ {
+ $factory = new StompConnectionFactory('stomp+rabbitmq://');
+
+ $context = $factory->createContext();
+
+ $this->assertInstanceOf(StompContext::class, $context);
+
+ $this->assertAttributeEquals(null, 'stomp', $context);
+ $this->assertAttributeEquals(true, 'useExchangePrefix', $context);
+ }
+
+ public function testShouldCreateActiveMQContext()
+ {
+ $factory = new StompConnectionFactory('stomp+activemq://');
+
+ $context = $factory->createContext();
+
+ $this->assertInstanceOf(StompContext::class, $context);
+
+ $this->assertAttributeEquals(null, 'stomp', $context);
+ $this->assertAttributeEquals(false, 'useExchangePrefix', $context);
}
}
diff --git a/pkg/stomp/Tests/StompConsumerTest.php b/pkg/stomp/Tests/StompConsumerTest.php
index 19b16096e..d461284c9 100644
--- a/pkg/stomp/Tests/StompConsumerTest.php
+++ b/pkg/stomp/Tests/StompConsumerTest.php
@@ -3,10 +3,12 @@
namespace Enqueue\Stomp\Tests;
use Enqueue\Stomp\BufferedStompClient;
+use Enqueue\Stomp\ExtensionType;
use Enqueue\Stomp\StompConsumer;
use Enqueue\Stomp\StompDestination;
use Enqueue\Stomp\StompMessage;
use Enqueue\Test\ClassExtensionTrait;
+use Enqueue\Test\ReadAttributeTrait;
use Interop\Queue\Consumer;
use Interop\Queue\Exception\InvalidMessageException;
use Interop\Queue\Message;
@@ -16,17 +18,13 @@
class StompConsumerTest extends \PHPUnit\Framework\TestCase
{
use ClassExtensionTrait;
+ use ReadAttributeTrait;
public function testShouldImplementMessageConsumerInterface()
{
$this->assertClassImplements(Consumer::class, StompConsumer::class);
}
- public function testCouldBeConstructedWithRequiredAttributes()
- {
- new StompConsumer($this->createStompClientMock(), $this->createDummyDestination());
- }
-
public function testCouldGetQueue()
{
$consumer = new StompConsumer($this->createStompClientMock(), $dest = $this->createDummyDestination());
@@ -520,8 +518,8 @@ public function testShouldGenerateUniqueSubscriptionIdPerConsumer()
$fooConsumer = new StompConsumer($this->createStompClientMock(), $destination);
$barConsumer = new StompConsumer($this->createStompClientMock(), $destination);
- $this->assertAttributeNotEmpty('subscriptionId', $fooConsumer);
- $this->assertAttributeNotEmpty('subscriptionId', $barConsumer);
+ $this->assertNotEmpty($this->readAttribute($fooConsumer, 'subscriptionId'));
+ $this->assertNotEmpty($this->readAttribute($barConsumer, 'subscriptionId'));
$fooSubscriptionId = $this->readAttribute($fooConsumer, 'subscriptionId');
$barSubscriptionId = $this->readAttribute($barConsumer, 'subscriptionId');
@@ -540,7 +538,7 @@ public function testShouldUseTempQueueNameAsSubscriptionId()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Protocol
+ * @return \PHPUnit\Framework\MockObject\MockObject|Protocol
*/
private function createStompProtocolMock()
{
@@ -548,7 +546,7 @@ private function createStompProtocolMock()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|BufferedStompClient
+ * @return \PHPUnit\Framework\MockObject\MockObject|BufferedStompClient
*/
private function createStompClientMock()
{
@@ -557,7 +555,7 @@ private function createStompClientMock()
private function createDummyDestination(): StompDestination
{
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setStompName('aName');
$destination->setType(StompDestination::TYPE_QUEUE);
diff --git a/pkg/stomp/Tests/StompContextTest.php b/pkg/stomp/Tests/StompContextTest.php
index 49297d3e1..cfb9245dc 100644
--- a/pkg/stomp/Tests/StompContextTest.php
+++ b/pkg/stomp/Tests/StompContextTest.php
@@ -3,6 +3,7 @@
namespace Enqueue\Stomp\Tests;
use Enqueue\Stomp\BufferedStompClient;
+use Enqueue\Stomp\ExtensionType;
use Enqueue\Stomp\StompConsumer;
use Enqueue\Stomp\StompContext;
use Enqueue\Stomp\StompDestination;
@@ -22,29 +23,17 @@ public function testShouldImplementSessionInterface()
$this->assertClassImplements(Context::class, StompContext::class);
}
- public function testCouldBeCreatedWithRequiredArguments()
- {
- new StompContext($this->createStompClientMock());
- }
-
- public function testCouldBeConstructedWithExtChannelCallbackFactoryAsFirstArgument()
- {
- new StompContext(function () {
- return $this->createStompClientMock();
- });
- }
-
public function testThrowIfNeitherCallbackNorExtChannelAsFirstArgument()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The stomp argument must be either BufferedStompClient or callable that return BufferedStompClient.');
- new StompContext(new \stdClass());
+ new StompContext(new \stdClass(), ExtensionType::RABBITMQ);
}
public function testShouldCreateMessageInstance()
{
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$message = $context->createMessage('the body', ['key' => 'value'], ['hkey' => 'hvalue']);
@@ -56,7 +45,7 @@ public function testShouldCreateMessageInstance()
public function testShouldCreateQueueInstance()
{
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$queue = $context->createQueue('the name');
@@ -68,7 +57,7 @@ public function testShouldCreateQueueInstance()
public function testCreateQueueShouldCreateDestinationIfNameIsFullDestinationString()
{
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$destination = $context->createQueue('/amq/queue/name/routing-key');
@@ -79,9 +68,9 @@ public function testCreateQueueShouldCreateDestinationIfNameIsFullDestinationStr
$this->assertEquals('/amq/queue/name/routing-key', $destination->getQueueName());
}
- public function testShouldCreateTopicInstance()
+ public function testShouldCreateTopicInstanceWithExchangePrefix()
{
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$topic = $context->createTopic('the name');
@@ -91,9 +80,21 @@ public function testShouldCreateTopicInstance()
$this->assertSame(StompDestination::TYPE_EXCHANGE, $topic->getType());
}
+ public function testShouldCreateTopicInstanceWithTopicPrefix()
+ {
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::ACTIVEMQ);
+
+ $topic = $context->createTopic('the name');
+
+ $this->assertInstanceOf(StompDestination::class, $topic);
+ $this->assertSame('/topic/the name', $topic->getQueueName());
+ $this->assertSame('/topic/the name', $topic->getTopicName());
+ $this->assertSame(StompDestination::TYPE_TOPIC, $topic->getType());
+ }
+
public function testCreateTopicShouldCreateDestinationIfNameIsFullDestinationString()
{
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$destination = $context->createTopic('/amq/queue/name/routing-key');
@@ -109,20 +110,20 @@ public function testThrowInvalidDestinationException()
$this->expectException(InvalidDestinationException::class);
$this->expectExceptionMessage('The destination must be an instance of');
- $session = new StompContext($this->createStompClientMock());
+ $session = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$session->createConsumer($this->createMock(Queue::class));
}
public function testShouldCreateMessageConsumerInstance()
{
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$this->assertInstanceOf(StompConsumer::class, $context->createConsumer($this->createDummyDestination()));
}
public function testShouldCreateMessageProducerInstance()
{
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$this->assertInstanceOf(StompProducer::class, $context->createProducer());
}
@@ -131,11 +132,11 @@ public function testShouldCloseConnections()
{
$client = $this->createStompClientMock();
$client
- ->expects($this->once())
+ ->expects($this->atLeastOnce())
->method('disconnect')
;
- $context = new StompContext($client);
+ $context = new StompContext($client, ExtensionType::RABBITMQ);
$context->createProducer();
$context->createConsumer($this->createDummyDestination());
@@ -148,7 +149,7 @@ public function testCreateDestinationShouldThrowLogicExceptionIfTypeIsInvalid()
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Destination name is invalid, cant find type: "/invalid-type/name"');
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$context->createDestination('/invalid-type/name');
}
@@ -157,7 +158,7 @@ public function testCreateDestinationShouldThrowLogicExceptionIfExtraSlashFound(
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Destination name is invalid, found extra / char: "/queue/name/routing-key/extra');
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$context->createDestination('/queue/name/routing-key/extra');
}
@@ -166,7 +167,7 @@ public function testCreateDestinationShouldThrowLogicExceptionIfNameIsEmpty()
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Destination name is invalid, name is empty: "/queue/"');
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$context->createDestination('/queue/');
}
@@ -175,13 +176,13 @@ public function testCreateDestinationShouldThrowLogicExceptionIfRoutingKeyIsEmpt
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Destination name is invalid, routing key is empty: "/queue/name/"');
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$context->createDestination('/queue/name/');
}
public function testCreateDestinationShouldParseStringAndCreateDestination()
{
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$destination = $context->createDestination('/amq/queue/name/routing-key');
$this->assertEquals('amq/queue', $destination->getType());
@@ -192,7 +193,7 @@ public function testCreateDestinationShouldParseStringAndCreateDestination()
public function testCreateTemporaryQueue()
{
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$tempQueue = $context->createTemporaryQueue();
$this->assertEquals('temp-queue', $tempQueue->getType());
@@ -203,7 +204,7 @@ public function testCreateTemporaryQueue()
public function testCreateTemporaryQueuesWithUniqueNames()
{
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$fooTempQueue = $context->createTemporaryQueue();
$barTempQueue = $context->createTemporaryQueue();
@@ -215,13 +216,13 @@ public function testCreateTemporaryQueuesWithUniqueNames()
public function testShouldGetBufferedStompClient()
{
- $context = new StompContext($this->createStompClientMock());
+ $context = new StompContext($this->createStompClientMock(), ExtensionType::RABBITMQ);
$this->assertInstanceOf(BufferedStompClient::class, $context->getStomp());
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|BufferedStompClient
+ * @return \PHPUnit\Framework\MockObject\MockObject|BufferedStompClient
*/
private function createStompClientMock()
{
@@ -230,7 +231,7 @@ private function createStompClientMock()
private function createDummyDestination(): StompDestination
{
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setStompName('aName');
$destination->setType(StompDestination::TYPE_QUEUE);
diff --git a/pkg/stomp/Tests/StompDestinationTest.php b/pkg/stomp/Tests/StompDestinationTest.php
index 0f5261866..5061655f8 100644
--- a/pkg/stomp/Tests/StompDestinationTest.php
+++ b/pkg/stomp/Tests/StompDestinationTest.php
@@ -2,6 +2,7 @@
namespace Enqueue\Stomp\Tests;
+use Enqueue\Stomp\ExtensionType;
use Enqueue\Stomp\StompDestination;
use Enqueue\Test\ClassExtensionTrait;
use Interop\Queue\Queue;
@@ -19,7 +20,7 @@ public function testShouldImplementsTopicAndQueueInterfaces()
public function testShouldReturnDestinationStringWithRoutingKey()
{
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_AMQ_QUEUE);
$destination->setStompName('name');
$destination->setRoutingKey('routing-key');
@@ -32,7 +33,7 @@ public function testShouldReturnDestinationStringWithRoutingKey()
public function testShouldReturnDestinationStringWithoutRoutingKey()
{
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_TOPIC);
$destination->setStompName('name');
@@ -47,7 +48,7 @@ public function testShouldThrowLogicExceptionIfNameIsNotSet()
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Destination name is not set');
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_QUEUE);
$destination->setStompName('');
@@ -59,7 +60,7 @@ public function testSetTypeShouldThrowLogicExceptionIfTypeIsInvalid()
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('Invalid destination type: "invalid-type"');
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType('invalid-type');
}
}
diff --git a/pkg/stomp/Tests/StompHeadersEncoderTest.php b/pkg/stomp/Tests/StompHeadersEncoderTest.php
index 7997e05a4..cd3d112dd 100644
--- a/pkg/stomp/Tests/StompHeadersEncoderTest.php
+++ b/pkg/stomp/Tests/StompHeadersEncoderTest.php
@@ -32,9 +32,6 @@ public function propertyValuesDataProvider()
/**
* @dataProvider headerValuesDataProvider
- *
- * @param mixed $originalValue
- * @param mixed $encodedValue
*/
public function testShouldEncodeHeaders($originalValue, $encodedValue)
{
@@ -43,9 +40,6 @@ public function testShouldEncodeHeaders($originalValue, $encodedValue)
/**
* @dataProvider propertyValuesDataProvider
- *
- * @param mixed $originalValue
- * @param mixed $encodedValue
*/
public function testShouldEncodeProperties($originalValue, $encodedValue)
{
@@ -54,9 +48,6 @@ public function testShouldEncodeProperties($originalValue, $encodedValue)
/**
* @dataProvider headerValuesDataProvider
- *
- * @param mixed $originalValue
- * @param mixed $encodedValue
*/
public function testShouldDecodeHeaders($originalValue, $encodedValue)
{
@@ -65,9 +56,6 @@ public function testShouldDecodeHeaders($originalValue, $encodedValue)
/**
* @dataProvider propertyValuesDataProvider
- *
- * @param mixed $originalValue
- * @param mixed $encodedValue
*/
public function testShouldDecodeProperties($originalValue, $encodedValue)
{
diff --git a/pkg/stomp/Tests/StompMessageTest.php b/pkg/stomp/Tests/StompMessageTest.php
index 736df79a2..49be1a8c5 100644
--- a/pkg/stomp/Tests/StompMessageTest.php
+++ b/pkg/stomp/Tests/StompMessageTest.php
@@ -93,7 +93,7 @@ public function testShouldUnsetHeaderIfNullPassed()
$message->setHeader('aHeader', 'aVal');
- //guard
+ // guard
$this->assertSame('aVal', $message->getHeader('aHeader'));
$message->setHeader('aHeader', null);
@@ -108,7 +108,7 @@ public function testShouldUnsetPropertyIfNullPassed()
$message->setProperty('aProperty', 'aVal');
- //guard
+ // guard
$this->assertSame('aVal', $message->getProperty('aProperty'));
$message->setProperty('aProperty', null);
diff --git a/pkg/stomp/Tests/StompProducerTest.php b/pkg/stomp/Tests/StompProducerTest.php
index a197a5870..41f35256c 100644
--- a/pkg/stomp/Tests/StompProducerTest.php
+++ b/pkg/stomp/Tests/StompProducerTest.php
@@ -2,6 +2,7 @@
namespace Enqueue\Stomp\Tests;
+use Enqueue\Stomp\ExtensionType;
use Enqueue\Stomp\StompDestination;
use Enqueue\Stomp\StompMessage;
use Enqueue\Stomp\StompProducer;
@@ -40,7 +41,7 @@ public function testShouldThrowInvalidMessageExceptionWhenMessageIsWrongType()
$producer = new StompProducer($this->createStompClientMock());
- $producer->send(new StompDestination(), $this->createMock(Message::class));
+ $producer->send(new StompDestination(ExtensionType::RABBITMQ), $this->createMock(Message::class));
}
public function testShouldSendMessage()
@@ -54,7 +55,7 @@ public function testShouldSendMessage()
$producer = new StompProducer($client);
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_QUEUE);
$destination->setStompName('name');
@@ -77,7 +78,7 @@ public function testShouldEncodeMessageHeadersAndProperties()
$message = new StompMessage('', ['key' => 'value'], ['hkey' => false]);
- $destination = new StompDestination();
+ $destination = new StompDestination(ExtensionType::RABBITMQ);
$destination->setType(StompDestination::TYPE_QUEUE);
$destination->setStompName('name');
@@ -100,7 +101,7 @@ public function testShouldEncodeMessageHeadersAndProperties()
}
/**
- * @return \PHPUnit_Framework_MockObject_MockObject|Client
+ * @return \PHPUnit\Framework\MockObject\MockObject|Client
*/
private function createStompClientMock()
{
diff --git a/pkg/stomp/composer.json b/pkg/stomp/composer.json
index 28e73f1ee..2cceb9fea 100644
--- a/pkg/stomp/composer.json
+++ b/pkg/stomp/composer.json
@@ -6,19 +6,21 @@
"homepage": "https://enqueue.forma-pro.com/",
"license": "MIT",
"require": {
- "php": "^7.1.3",
- "enqueue/dsn": "0.9.x-dev",
- "stomp-php/stomp-php": "^4",
- "queue-interop/queue-interop": "0.7.x-dev",
- "php-http/guzzle6-adapter": "^1.1",
- "php-http/client-common": "^1.7@dev",
- "richardfullmer/rabbitmq-management-api": "^2.0"
+ "php": "^8.1",
+ "enqueue/dsn": "^0.10",
+ "stomp-php/stomp-php": "^4.5|^5.0",
+ "queue-interop/queue-interop": "^0.8",
+ "php-http/guzzle7-adapter": "^0.1.1",
+ "php-http/client-common": "^2.2.1",
+ "andrewmy/rabbitmq-management-api": "^2.1.2",
+ "guzzlehttp/guzzle": "^7.0.1",
+ "php-http/discovery": "^1.13"
},
"require-dev": {
- "phpunit/phpunit": "~5.4.0",
- "enqueue/test": "0.9.x-dev",
- "enqueue/null": "0.9.x-dev",
- "queue-interop/queue-spec": "0.6.x-dev"
+ "phpunit/phpunit": "^9.5",
+ "enqueue/test": "0.10.x-dev",
+ "enqueue/null": "0.10.x-dev",
+ "queue-interop/queue-spec": "^0.6.2"
},
"support": {
"email": "opensource@forma-pro.com",
@@ -36,7 +38,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/stomp/phpunit.xml.dist b/pkg/stomp/phpunit.xml.dist
index a9291bf93..ae7136aca 100644
--- a/pkg/stomp/phpunit.xml.dist
+++ b/pkg/stomp/phpunit.xml.dist
@@ -1,16 +1,11 @@
-
+
diff --git a/pkg/test/GpsExtension.php b/pkg/test/GpsExtension.php
index 6d9c412b6..2b03ef64b 100644
--- a/pkg/test/GpsExtension.php
+++ b/pkg/test/GpsExtension.php
@@ -4,13 +4,14 @@
use Enqueue\Gps\GpsConnectionFactory;
use Enqueue\Gps\GpsContext;
+use PHPUnit\Framework\SkippedTestError;
trait GpsExtension
{
private function buildGpsContext(): GpsContext
{
if (false == getenv('GPS_DSN')) {
- throw new \PHPUnit_Framework_SkippedTestError('Functional tests are not allowed in this environment');
+ throw new SkippedTestError('Functional tests are not allowed in this environment');
}
$config = getenv('GPS_DSN');
diff --git a/pkg/test/README.md b/pkg/test/README.md
index cb8ded237..e1ab96a9d 100644
--- a/pkg/test/README.md
+++ b/pkg/test/README.md
@@ -1,24 +1,37 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
# Message Queue. Test utils
[](https://gitter.im/php-enqueue/Lobby)
-
-Contains stuff needed in tests. Shared among different packages.
+
+Contains stuff needed in tests. Shared among different packages.
## Resources
* [Site](https://enqueue.forma-pro.com/)
-* [Documentation](https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md)
+* [Documentation](https://php-enqueue.github.io/)
* [Questions](https://gitter.im/php-enqueue/Lobby)
* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
-## Developed by Forma-Pro
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
-Forma-Pro is a full stack development company which interests also spread to open source development.
-Being a team of strong professionals we have an aim an ability to help community by developing cutting edge solutions in the areas of e-commerce, docker & microservice oriented architecture where we have accumulated a huge many-years experience.
-Our main specialization is Symfony framework based solution, but we are always looking to the technologies that allow us to do our job the best way. We are committed to creating solutions that revolutionize the way how things are developed in aspects of architecture & scalability.
+Learn more at [forma-pro.com](https://forma-pro.com).
-If you have any questions and inquires about our open source development, this product particularly or any other matter feel free to contact at opensource@forma-pro.com
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
## License
-It is released under the [MIT License](LICENSE).
\ No newline at end of file
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/test/RabbitManagementExtensionTrait.php b/pkg/test/RabbitManagementExtensionTrait.php
index 0940874ab..184b1758e 100644
--- a/pkg/test/RabbitManagementExtensionTrait.php
+++ b/pkg/test/RabbitManagementExtensionTrait.php
@@ -11,7 +11,7 @@ trait RabbitManagementExtensionTrait
*/
private function removeQueue($queueName)
{
- $dsn = new Dsn(getenv('RABBITMQ_AMQP_DSN'));
+ $dsn = Dsn::parseFirst(getenv('RABBITMQ_AMQP_DSN'));
$url = sprintf(
'http://%s:15672/api/queues/%s/%s',
@@ -21,17 +21,17 @@ private function removeQueue($queueName)
);
$ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
- curl_setopt($ch, CURLOPT_USERPWD, $dsn->getUser().':'.$dsn->getPassword());
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ curl_setopt($ch, \CURLOPT_URL, $url);
+ curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'DELETE');
+ curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch, \CURLOPT_HTTPAUTH, \CURLAUTH_BASIC);
+ curl_setopt($ch, \CURLOPT_USERPWD, $dsn->getUser().':'.$dsn->getPassword());
+ curl_setopt($ch, \CURLOPT_HTTPHEADER, [
'Content-Type' => 'application/json',
]);
curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ $httpCode = curl_getinfo($ch, \CURLINFO_HTTP_CODE);
curl_close($ch);
@@ -45,7 +45,7 @@ private function removeQueue($queueName)
*/
private function removeExchange($exchangeName)
{
- $dsn = new Dsn(getenv('RABBITMQ_AMQP_DSN'));
+ $dsn = Dsn::parseFirst(getenv('RABBITMQ_AMQP_DSN'));
$url = sprintf(
'http://%s:15672/api/exchanges/%s/%s',
@@ -55,17 +55,17 @@ private function removeExchange($exchangeName)
);
$ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
- curl_setopt($ch, CURLOPT_USERPWD, $dsn->getUser().':'.$dsn->getPassword());
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ curl_setopt($ch, \CURLOPT_URL, $url);
+ curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'DELETE');
+ curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch, \CURLOPT_HTTPAUTH, \CURLAUTH_BASIC);
+ curl_setopt($ch, \CURLOPT_USERPWD, $dsn->getUser().':'.$dsn->getPassword());
+ curl_setopt($ch, \CURLOPT_HTTPHEADER, [
'Content-Type' => 'application/json',
]);
curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ $httpCode = curl_getinfo($ch, \CURLINFO_HTTP_CODE);
curl_close($ch);
diff --git a/pkg/test/RabbitmqAmqpExtension.php b/pkg/test/RabbitmqAmqpExtension.php
index 358147851..28099f12b 100644
--- a/pkg/test/RabbitmqAmqpExtension.php
+++ b/pkg/test/RabbitmqAmqpExtension.php
@@ -4,6 +4,7 @@
use Enqueue\AmqpExt\AmqpConnectionFactory;
use Enqueue\AmqpExt\AmqpContext;
+use PHPUnit\Framework\SkippedTestError;
trait RabbitmqAmqpExtension
{
@@ -13,7 +14,7 @@ trait RabbitmqAmqpExtension
private function buildAmqpContext()
{
if (false == $dsn = getenv('AMQP_DSN')) {
- throw new \PHPUnit_Framework_SkippedTestError('Functional tests are not allowed in this environment');
+ throw new SkippedTestError('Functional tests are not allowed in this environment');
}
return (new AmqpConnectionFactory($dsn))->createContext();
diff --git a/pkg/test/RabbitmqStompExtension.php b/pkg/test/RabbitmqStompExtension.php
index 2ce2dfaa0..240f67edb 100644
--- a/pkg/test/RabbitmqStompExtension.php
+++ b/pkg/test/RabbitmqStompExtension.php
@@ -4,13 +4,19 @@
use Enqueue\Stomp\StompConnectionFactory;
use Enqueue\Stomp\StompContext;
+use PHPUnit\Framework\SkippedTestError;
trait RabbitmqStompExtension
{
+ private function getDsn()
+ {
+ return getenv('RABITMQ_STOMP_DSN');
+ }
+
private function buildStompContext(): StompContext
{
- if (false == $dsn = getenv('RABITMQ_STOMP_DSN')) {
- throw new \PHPUnit_Framework_SkippedTestError('Functional tests are not allowed in this environment');
+ if (false == $dsn = $this->getDsn()) {
+ throw new SkippedTestError('Functional tests are not allowed in this environment');
}
return (new StompConnectionFactory($dsn))->createContext();
diff --git a/pkg/test/ReadAttributeTrait.php b/pkg/test/ReadAttributeTrait.php
new file mode 100644
index 000000000..2b0208764
--- /dev/null
+++ b/pkg/test/ReadAttributeTrait.php
@@ -0,0 +1,52 @@
+getClassAttribute($object, $attribute)->getValue($object);
+ }
+
+ private function getClassAttribute(
+ object $object,
+ string $attribute,
+ ?string $class = null,
+ ): \ReflectionProperty {
+ if (null === $class) {
+ $class = $object::class;
+ }
+
+ try {
+ return new \ReflectionProperty($class, $attribute);
+ } catch (\ReflectionException $exception) {
+ $parentClass = get_parent_class($object);
+ if (false === $parentClass) {
+ throw $exception;
+ }
+
+ return $this->getClassAttribute($object, $attribute, $parentClass);
+ }
+ }
+
+ private function assertAttributeSame($expected, string $attribute, object $object): void
+ {
+ static::assertSame($expected, $this->readAttribute($object, $attribute));
+ }
+
+ private function assertAttributeEquals($expected, string $attribute, object $object): void
+ {
+ static::assertEquals($expected, $this->readAttribute($object, $attribute));
+ }
+
+ private function assertAttributeInstanceOf(string $expected, string $attribute, object $object): void
+ {
+ static::assertInstanceOf($expected, $this->readAttribute($object, $attribute));
+ }
+
+ private function assertAttributeCount(int $count, string $attribute, object $object): void
+ {
+ static::assertCount($count, $this->readAttribute($object, $attribute));
+ }
+}
diff --git a/pkg/test/RedisExtension.php b/pkg/test/RedisExtension.php
index cb32382f9..3227785c2 100644
--- a/pkg/test/RedisExtension.php
+++ b/pkg/test/RedisExtension.php
@@ -6,20 +6,21 @@
use Enqueue\Redis\PRedis;
use Enqueue\Redis\RedisConnectionFactory;
use Enqueue\Redis\RedisContext;
+use PHPUnit\Framework\SkippedTestError;
trait RedisExtension
{
private function buildPhpRedisContext(): RedisContext
{
if (false == getenv('PHPREDIS_DSN')) {
- throw new \PHPUnit_Framework_SkippedTestError('Functional tests are not allowed in this environment');
+ throw new SkippedTestError('Functional tests are not allowed in this environment');
}
$config = getenv('PHPREDIS_DSN');
$context = (new RedisConnectionFactory($config))->createContext();
- //guard
+ // guard
$this->assertInstanceOf(PhpRedis::class, $context->getRedis());
return $context;
@@ -28,14 +29,14 @@ private function buildPhpRedisContext(): RedisContext
private function buildPRedisContext(): RedisContext
{
if (false == getenv('PREDIS_DSN')) {
- throw new \PHPUnit_Framework_SkippedTestError('Functional tests are not allowed in this environment');
+ throw new SkippedTestError('Functional tests are not allowed in this environment');
}
$config = getenv('PREDIS_DSN');
$context = (new RedisConnectionFactory($config))->createContext();
- //guard
+ // guard
$this->assertInstanceOf(PRedis::class, $context->getRedis());
return $context;
diff --git a/pkg/test/RetryTrait.php b/pkg/test/RetryTrait.php
index de17565bd..1f1042c81 100644
--- a/pkg/test/RetryTrait.php
+++ b/pkg/test/RetryTrait.php
@@ -2,9 +2,13 @@
namespace Enqueue\Test;
+use PHPUnit\Framework\IncompleteTestError;
+use PHPUnit\Framework\SkippedTestError;
+use PHPUnit\Util\Test;
+
trait RetryTrait
{
- public function runBare()
+ public function runBare(): void
{
$e = null;
@@ -22,9 +26,9 @@ public function runBare()
parent::runBare();
return;
- } catch (\PHPUnit_Framework_IncompleteTestError $e) {
+ } catch (IncompleteTestError $e) {
throw $e;
- } catch (\PHPUnit_Framework_SkippedTestError $e) {
+ } catch (SkippedTestError $e) {
throw $e;
} catch (\Throwable $e) {
// last one thrown below
@@ -43,7 +47,7 @@ public function runBare()
*/
private function getNumberOfRetries()
{
- $annotations = $this->getAnnotations();
+ $annotations = Test::parseTestMethodAnnotations(static::class, $this->getName(false));
if (isset($annotations['method']['retry'][0])) {
return $annotations['method']['retry'][0];
diff --git a/pkg/test/SnsExtension.php b/pkg/test/SnsExtension.php
new file mode 100644
index 000000000..050f212dd
--- /dev/null
+++ b/pkg/test/SnsExtension.php
@@ -0,0 +1,19 @@
+createContext();
+ }
+}
diff --git a/pkg/test/SnsQsExtension.php b/pkg/test/SnsQsExtension.php
new file mode 100644
index 000000000..6dc7dc9d9
--- /dev/null
+++ b/pkg/test/SnsQsExtension.php
@@ -0,0 +1,19 @@
+createContext();
+ }
+}
diff --git a/pkg/test/SqsExtension.php b/pkg/test/SqsExtension.php
index 3cc17e47f..c00b42e68 100644
--- a/pkg/test/SqsExtension.php
+++ b/pkg/test/SqsExtension.php
@@ -4,13 +4,14 @@
use Enqueue\Sqs\SqsConnectionFactory;
use Enqueue\Sqs\SqsContext;
+use PHPUnit\Framework\SkippedTestError;
trait SqsExtension
{
private function buildSqsContext(): SqsContext
{
if (false == $dsn = getenv('SQS_DSN')) {
- throw new \PHPUnit_Framework_SkippedTestError('Functional tests are not allowed in this environment');
+ throw new SkippedTestError('Functional tests are not allowed in this environment');
}
return (new SqsConnectionFactory($dsn))->createContext();
diff --git a/pkg/test/TestLogger.php b/pkg/test/TestLogger.php
new file mode 100644
index 000000000..9db2c2a5e
--- /dev/null
+++ b/pkg/test/TestLogger.php
@@ -0,0 +1,144 @@
+ 0) {
+ $genericMethod = $matches[1].('Records' !== $matches[3] ? 'Record' : '').$matches[3];
+ $level = strtolower($matches[2]);
+ if (method_exists($this, $genericMethod)) {
+ $args[] = $level;
+
+ return call_user_func_array([$this, $genericMethod], $args);
+ }
+ }
+ throw new \BadMethodCallException('Call to undefined method TestLogger::'.$method.'()');
+ }
+
+ public function log($level, $message, array $context = []): void
+ {
+ $record = [
+ 'level' => $level,
+ 'message' => $message,
+ 'context' => $context,
+ ];
+
+ $this->recordsByLevel[$record['level']][] = $record;
+ $this->records[] = $record;
+ }
+
+ public function hasRecords($level)
+ {
+ return isset($this->recordsByLevel[$level]);
+ }
+
+ public function hasRecord($record, $level)
+ {
+ if (is_string($record)) {
+ $record = ['message' => $record];
+ }
+
+ return $this->hasRecordThatPasses(function ($rec) use ($record) {
+ if ($rec['message'] !== $record['message']) {
+ return false;
+ }
+ if (isset($record['context']) && $rec['context'] !== $record['context']) {
+ return false;
+ }
+
+ return true;
+ }, $level);
+ }
+
+ public function hasRecordThatContains($message, $level)
+ {
+ return $this->hasRecordThatPasses(function ($rec) use ($message) {
+ return str_contains($rec['message'], $message);
+ }, $level);
+ }
+
+ public function hasRecordThatMatches($regex, $level)
+ {
+ return $this->hasRecordThatPasses(function ($rec) use ($regex) {
+ return preg_match($regex, $rec['message']) > 0;
+ }, $level);
+ }
+
+ public function hasRecordThatPasses(callable $predicate, $level)
+ {
+ if (!isset($this->recordsByLevel[$level])) {
+ return false;
+ }
+ foreach ($this->recordsByLevel[$level] as $i => $rec) {
+ if (call_user_func($predicate, $rec, $i)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public function reset()
+ {
+ $this->records = [];
+ $this->recordsByLevel = [];
+ }
+}
diff --git a/pkg/test/WampExtension.php b/pkg/test/WampExtension.php
new file mode 100644
index 000000000..5b17fe7cf
--- /dev/null
+++ b/pkg/test/WampExtension.php
@@ -0,0 +1,19 @@
+createContext();
+ }
+}
diff --git a/pkg/test/WriteAttributeTrait.php b/pkg/test/WriteAttributeTrait.php
index e2e84bd2a..6f8c1aab5 100644
--- a/pkg/test/WriteAttributeTrait.php
+++ b/pkg/test/WriteAttributeTrait.php
@@ -7,11 +7,10 @@ trait WriteAttributeTrait
/**
* @param object $object
* @param string $attribute
- * @param mixed $value
*/
public function writeAttribute($object, $attribute, $value)
{
- $refProperty = new \ReflectionProperty(get_class($object), $attribute);
+ $refProperty = new \ReflectionProperty($object::class, $attribute);
$refProperty->setAccessible(true);
$refProperty->setValue($object, $value);
$refProperty->setAccessible(false);
diff --git a/pkg/test/composer.json b/pkg/test/composer.json
index 1cf9f5482..ad9234cda 100644
--- a/pkg/test/composer.json
+++ b/pkg/test/composer.json
@@ -10,7 +10,7 @@
"docs": "https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md"
},
"require": {
- "enqueue/dsn": "0.9.x-dev"
+ "enqueue/dsn": "^0.10"
},
"autoload": {
"psr-4": { "Enqueue\\Test\\": "" }
@@ -18,7 +18,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
- "dev-master": "0.9.x-dev"
+ "dev-master": "0.10.x-dev"
}
}
}
diff --git a/pkg/wamp/.gitattributes b/pkg/wamp/.gitattributes
new file mode 100644
index 000000000..bdf2dcb14
--- /dev/null
+++ b/pkg/wamp/.gitattributes
@@ -0,0 +1,5 @@
+/Tests export-ignore
+.gitattributes export-ignore
+.gitignore export-ignore
+.travis.yml export-ignore
+phpunit.xml.dist export-ignore
diff --git a/pkg/wamp/.github/workflows/ci.yml b/pkg/wamp/.github/workflows/ci.yml
new file mode 100644
index 000000000..ce80335de
--- /dev/null
+++ b/pkg/wamp/.github/workflows/ci.yml
@@ -0,0 +1,27 @@
+name: CI
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+jobs:
+ tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ php: ['8.2', '8.3', '8.4']
+
+ name: PHP ${{ matrix.php }} tests
+
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ coverage: none
+
+ - uses: "ramsey/composer-install@v3"
+
+ - run: vendor/bin/phpunit --exclude-group=functional
diff --git a/pkg/wamp/.gitignore b/pkg/wamp/.gitignore
new file mode 100644
index 000000000..a770439e5
--- /dev/null
+++ b/pkg/wamp/.gitignore
@@ -0,0 +1,6 @@
+*~
+/composer.lock
+/composer.phar
+/phpunit.xml
+/vendor/
+/.idea/
diff --git a/pkg/wamp/JsonSerializer.php b/pkg/wamp/JsonSerializer.php
new file mode 100644
index 000000000..9a224fbb8
--- /dev/null
+++ b/pkg/wamp/JsonSerializer.php
@@ -0,0 +1,33 @@
+ $message->getBody(),
+ 'properties' => $message->getProperties(),
+ 'headers' => $message->getHeaders(),
+ ]);
+
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
+ }
+
+ return $json;
+ }
+
+ public function toMessage(string $string): WampMessage
+ {
+ $data = json_decode($string, true);
+ if (\JSON_ERROR_NONE !== json_last_error()) {
+ throw new \InvalidArgumentException(sprintf('The malformed json given. Error %s and message %s', json_last_error(), json_last_error_msg()));
+ }
+
+ return new WampMessage($data['body'], $data['properties'], $data['headers']);
+ }
+}
diff --git a/pkg/wamp/LICENSE b/pkg/wamp/LICENSE
new file mode 100644
index 000000000..7afbaa1ff
--- /dev/null
+++ b/pkg/wamp/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+Copyright (c) 2018 Forma-Pro
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished
+to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/pkg/wamp/README.md b/pkg/wamp/README.md
new file mode 100644
index 000000000..e0a98ae91
--- /dev/null
+++ b/pkg/wamp/README.md
@@ -0,0 +1,40 @@
+Supporting Enqueue
+
+Enqueue is an MIT-licensed open source project with its ongoing development made possible entirely by the support of community and our customers. If you'd like to join them, please consider:
+
+- [Become a sponsor](https://www.patreon.com/makasim)
+- [Become our client](http://forma-pro.com/)
+
+---
+
+# Web Application Messaging Protocol (WAMP) Transport
+
+[](https://gitter.im/php-enqueue/Lobby)
+[](https://github.com/php-enqueue/wamp/actions?query=workflow%3ACI)
+[](https://packagist.org/packages/enqueue/wamp)
+[](https://packagist.org/packages/enqueue/wamp)
+
+This is an implementation of [queue interop](https://github.com/queue-interop/queue-interop). It uses [Thruway](https://github.com/thruway/client) internally.
+
+## Resources
+
+* [Site](https://enqueue.forma-pro.com/)
+* [Documentation](https://php-enqueue.github.io/transport/wamp/)
+* [Questions](https://gitter.im/php-enqueue/Lobby)
+* [Issue Tracker](https://github.com/php-enqueue/enqueue-dev/issues)
+
+## Developed by Forma Pro
+
+Forma Pro is a senior product engineering company helping product organizations build and evolve complex, data-intensive software.
+
+Our public open-source work reflects more than two decades of engineering history, including PHP/Symfony libraries, infrastructure tooling, workflow components, and messaging systems.
+
+Today, our work spans marketplaces and platforms, partner and attribution systems, FinTech, logistics, EdTech, data-intensive workflows, matching and recommendation systems, and applied AI/ML.
+
+Learn more at [forma-pro.com](https://forma-pro.com).
+
+For questions about this project or our open-source work, contact us at opensource@forma-pro.com.
+
+## License
+
+It is released under the [MIT License](LICENSE).
diff --git a/pkg/wamp/Serializer.php b/pkg/wamp/Serializer.php
new file mode 100644
index 000000000..414fcf414
--- /dev/null
+++ b/pkg/wamp/Serializer.php
@@ -0,0 +1,12 @@
+serializer = $serializer;
+ }
+
+ /**
+ * @return Serializer
+ */
+ public function getSerializer()
+ {
+ return $this->serializer;
+ }
+}
diff --git a/pkg/wamp/Tests/Functional/WampConsumerTest.php b/pkg/wamp/Tests/Functional/WampConsumerTest.php
new file mode 100644
index 000000000..bb2dd89a4
--- /dev/null
+++ b/pkg/wamp/Tests/Functional/WampConsumerTest.php
@@ -0,0 +1,69 @@
+buildWampContext();
+ $topic = $context->createTopic('topic');
+ $consumer = $context->createConsumer($topic);
+ $producer = $context->createProducer();
+ $message = $context->createMessage('the body');
+
+ // init client
+ $consumer->receive(1);
+
+ $consumer->getClient()->getLoop()->futureTick(function () use ($producer, $topic, $message) {
+ $producer->send($topic, $message);
+ });
+
+ $receivedMessage = $consumer->receive(100);
+
+ $this->assertInstanceOf(WampMessage::class, $receivedMessage);
+ $this->assertSame('the body', $receivedMessage->getBody());
+ }
+
+ public function testShouldSendAndReceiveNoWaitMessage()
+ {
+ $context = $this->buildWampContext();
+ $topic = $context->createTopic('topic');
+ $consumer = $context->createConsumer($topic);
+ $producer = $context->createProducer();
+ $message = $context->createMessage('the body');
+
+ // init client
+ $consumer->receive(1);
+
+ $consumer->getClient()->getLoop()->futureTick(function () use ($producer, $topic, $message) {
+ $producer->send($topic, $message);
+ });
+
+ $receivedMessage = $consumer->receiveNoWait();
+
+ $this->assertInstanceOf(WampMessage::class, $receivedMessage);
+ $this->assertSame('the body', $receivedMessage->getBody());
+ }
+}
diff --git a/pkg/wamp/Tests/Functional/WampSubscriptionConsumerTest.php b/pkg/wamp/Tests/Functional/WampSubscriptionConsumerTest.php
new file mode 100644
index 000000000..e272f42ed
--- /dev/null
+++ b/pkg/wamp/Tests/Functional/WampSubscriptionConsumerTest.php
@@ -0,0 +1,51 @@
+buildWampContext();
+ $topic = $context->createTopic('topic');
+ $consumer = $context->createSubscriptionConsumer();
+ $producer = $context->createProducer();
+ $message = $context->createMessage('the body');
+
+ $receivedMessage = null;
+ $consumer->subscribe($context->createConsumer($topic), function ($message) use (&$receivedMessage) {
+ $receivedMessage = $message;
+
+ return false;
+ });
+
+ // init client
+ $consumer->consume(1);
+
+ $consumer->getClient()->getLoop()->futureTick(function () use ($producer, $topic, $message) {
+ $producer->send($topic, $message);
+ });
+
+ $consumer->consume(100);
+
+ $this->assertInstanceOf(WampMessage::class, $receivedMessage);
+ $this->assertSame('the body', $receivedMessage->getBody());
+ }
+}
diff --git a/pkg/wamp/Tests/Spec/JsonSerializerTest.php b/pkg/wamp/Tests/Spec/JsonSerializerTest.php
new file mode 100644
index 000000000..f062a7058
--- /dev/null
+++ b/pkg/wamp/Tests/Spec/JsonSerializerTest.php
@@ -0,0 +1,71 @@
+assertClassImplements(Serializer::class, JsonSerializer::class);
+ }
+
+ public function testShouldConvertMessageToJsonString()
+ {
+ $serializer = new JsonSerializer();
+
+ $message = new WampMessage('theBody', ['aProp' => 'aPropVal'], ['aHeader' => 'aHeaderVal']);
+
+ $json = $serializer->toString($message);
+
+ $this->assertSame('{"body":"theBody","properties":{"aProp":"aPropVal"},"headers":{"aHeader":"aHeaderVal"}}', $json);
+ }
+
+ public function testThrowIfFailedToEncodeMessageToJson()
+ {
+ $serializer = new JsonSerializer();
+
+ $resource = fopen(__FILE__, 'r');
+
+ // guard
+ $this->assertIsResource($resource);
+
+ $message = new WampMessage('theBody', ['aProp' => $resource]);
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The malformed json given.');
+ $serializer->toString($message);
+ }
+
+ public function testShouldConvertJsonStringToMessage()
+ {
+ $serializer = new JsonSerializer();
+
+ $message = $serializer->toMessage('{"body":"theBody","properties":{"aProp":"aPropVal"},"headers":{"aHeader":"aHeaderVal"}}');
+
+ $this->assertInstanceOf(WampMessage::class, $message);
+
+ $this->assertSame('theBody', $message->getBody());
+ $this->assertSame(['aProp' => 'aPropVal'], $message->getProperties());
+ $this->assertSame(['aHeader' => 'aHeaderVal'], $message->getHeaders());
+ }
+
+ public function testThrowIfFailedToDecodeJsonToMessage()
+ {
+ $serializer = new JsonSerializer();
+
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('The malformed json given.');
+ $serializer->toMessage('{]');
+ }
+}
diff --git a/pkg/wamp/Tests/Spec/WampConnectionFactoryTest.php b/pkg/wamp/Tests/Spec/WampConnectionFactoryTest.php
new file mode 100644
index 000000000..5b6e418c9
--- /dev/null
+++ b/pkg/wamp/Tests/Spec/WampConnectionFactoryTest.php
@@ -0,0 +1,17 @@
+buildWampContext();
+ }
+}
diff --git a/pkg/wamp/Tests/Spec/WampMessageTest.php b/pkg/wamp/Tests/Spec/WampMessageTest.php
new file mode 100644
index 000000000..3e030d8c1
--- /dev/null
+++ b/pkg/wamp/Tests/Spec/WampMessageTest.php
@@ -0,0 +1,17 @@
+buildWampContext()->createProducer();
+ }
+}
diff --git a/pkg/wamp/Tests/Spec/WampQueueTest.php b/pkg/wamp/Tests/Spec/WampQueueTest.php
new file mode 100644
index 000000000..015536fd1
--- /dev/null
+++ b/pkg/wamp/Tests/Spec/WampQueueTest.php
@@ -0,0 +1,17 @@
+ 'wamp://127.0.0.1:9090',
+ * 'host' => '127.0.0.1',
+ * 'port' => '9090',
+ * 'max_retries' => 15,
+ * 'initial_retry_delay' => 1.5,
+ * 'max_retry_delay' => 300,
+ * 'retry_delay_growth' => 1.5,
+ * ]
+ *
+ * or
+ *
+ * wamp://127.0.0.1:9090?max_retries=10
+ *
+ * @param array|string|null $config
+ */
+ public function __construct($config = 'wamp:')
+ {
+ if (empty($config)) {
+ $config = $this->parseDsn('wamp:');
+ } elseif (is_string($config)) {
+ $config = $this->parseDsn($config);
+ } elseif (is_array($config)) {
+ $config = empty($config['dsn']) ? $config : $this->parseDsn($config['dsn']);
+ } else {
+ throw new \LogicException('The config must be either an array of options, a DSN string or null');
+ }
+
+ $config = array_replace([
+ 'host' => '127.0.0.1',
+ 'port' => '9090',
+ 'max_retries' => 15,
+ 'initial_retry_delay' => 1.5,
+ 'max_retry_delay' => 300,
+ 'retry_delay_growth' => 1.5,
+ ], $config);
+
+ $this->config = $config;
+ }
+
+ public function createContext(): Context
+ {
+ return new WampContext(function () {
+ return $this->establishConnection();
+ });
+ }
+
+ private function establishConnection(): Client
+ {
+ $uri = sprintf('ws://%s:%s', $this->config['host'], $this->config['port']);
+
+ $client = new Client('realm1');
+ $client->addTransportProvider(new PawlTransportProvider($uri));
+ $client->setReconnectOptions([
+ 'max_retries' => $this->config['max_retries'],
+ 'initial_retry_delay' => $this->config['initial_retry_delay'],
+ 'max_retry_delay' => $this->config['max_retry_delay'],
+ 'retry_delay_growth' => $this->config['retry_delay_growth'],
+ ]);
+
+ return $client;
+ }
+
+ private function parseDsn(string $dsn): array
+ {
+ $dsn = Dsn::parseFirst($dsn);
+
+ if (false === in_array($dsn->getSchemeProtocol(), ['wamp', 'ws'], true)) {
+ throw new \LogicException(sprintf('The given scheme protocol "%s" is not supported. It must be "wamp"', $dsn->getSchemeProtocol()));
+ }
+
+ return array_filter(array_replace($dsn->getQuery(), [
+ 'host' => $dsn->getHost(),
+ 'port' => $dsn->getPort(),
+ 'max_retries' => $dsn->getDecimal('max_retries'),
+ 'initial_retry_delay' => $dsn->getFloat('initial_retry_delay'),
+ 'max_retry_delay' => $dsn->getDecimal('max_retry_delay'),
+ 'retry_delay_growth' => $dsn->getFloat('retry_delay_growth'),
+ ]), function ($value) { return null !== $value; });
+ }
+}
diff --git a/pkg/wamp/WampConsumer.php b/pkg/wamp/WampConsumer.php
new file mode 100644
index 000000000..8a6733e36
--- /dev/null
+++ b/pkg/wamp/WampConsumer.php
@@ -0,0 +1,135 @@
+context = $context;
+ $this->queue = $destination;
+ }
+
+ public function getQueue(): Queue
+ {
+ return $this->queue;
+ }
+
+ public function getClient(): ?Client
+ {
+ return $this->client;
+ }
+
+ public function receive(int $timeout = 0): ?Message
+ {
+ $init = false;
+ $this->timer = null;
+ $this->message = null;
+
+ if (null === $this->client) {
+ $init = true;
+
+ $this->client = $this->context->getNewClient();
+ $this->client->setAttemptRetry(true);
+ $this->client->on('open', function (ClientSession $session) {
+ $session->subscribe($this->queue->getQueueName(), function ($args) {
+ $this->message = $this->context->getSerializer()->toMessage($args[0]);
+
+ $this->client->emit('do-stop');
+ });
+ });
+
+ $this->client->on('do-stop', function () {
+ if ($this->timer) {
+ $this->client->getLoop()->cancelTimer($this->timer);
+ }
+
+ $this->client->getLoop()->stop();
+ });
+ }
+
+ if ($timeout > 0) {
+ $timeout /= 1000;
+ $timeout = $timeout >= 0.1 ? $timeout : 0.1;
+
+ $this->timer = $this->client->getLoop()->addTimer($timeout, function () {
+ $this->client->emit('do-stop');
+ });
+ }
+
+ if ($init) {
+ $this->client->start(false);
+ }
+
+ $this->client->getLoop()->run();
+
+ $message = $this->message;
+
+ $this->timer = null;
+ $this->message = null;
+
+ return $message;
+ }
+
+ public function receiveNoWait(): ?Message
+ {
+ return $this->receive(100);
+ }
+
+ /**
+ * @param WampMessage $message
+ */
+ public function acknowledge(Message $message): void
+ {
+ // do nothing. wamp transport always works in auto ack mode
+ }
+
+ /**
+ * @param WampMessage $message
+ */
+ public function reject(Message $message, bool $requeue = false): void
+ {
+ InvalidMessageException::assertMessageInstanceOf($message, WampMessage::class);
+
+ // do nothing on reject. wamp transport always works in auto ack mode
+
+ if ($requeue) {
+ $this->context->createProducer()->send($this->queue, $message);
+ }
+ }
+}
diff --git a/pkg/wamp/WampContext.php b/pkg/wamp/WampContext.php
new file mode 100644
index 000000000..623aa33f9
--- /dev/null
+++ b/pkg/wamp/WampContext.php
@@ -0,0 +1,107 @@
+clientFactory = $clientFactory;
+
+ $this->setSerializer(new JsonSerializer());
+ }
+
+ public function createMessage(string $body = '', array $properties = [], array $headers = []): Message
+ {
+ return new WampMessage($body, $properties, $headers);
+ }
+
+ public function createTopic(string $topicName): Topic
+ {
+ return new WampDestination($topicName);
+ }
+
+ public function createQueue(string $queueName): Queue
+ {
+ return new WampDestination($queueName);
+ }
+
+ public function createTemporaryQueue(): Queue
+ {
+ throw TemporaryQueueNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function createProducer(): Producer
+ {
+ return new WampProducer($this);
+ }
+
+ public function createConsumer(Destination $destination): Consumer
+ {
+ InvalidDestinationException::assertDestinationInstanceOf($destination, WampDestination::class);
+
+ return new WampConsumer($this, $destination);
+ }
+
+ public function createSubscriptionConsumer(): SubscriptionConsumer
+ {
+ return new WampSubscriptionConsumer($this);
+ }
+
+ public function purgeQueue(Queue $queue): void
+ {
+ throw PurgeQueueNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function close(): void
+ {
+ foreach ($this->clients as $client) {
+ if (null === $client->getSession()) {
+ return;
+ }
+
+ $client->setAttemptRetry(false);
+ $client->getSession()->close();
+ }
+ }
+
+ public function getNewClient(): Client
+ {
+ $client = call_user_func($this->clientFactory);
+
+ if (false == $client instanceof Client) {
+ throw new \LogicException(sprintf('The factory must return instance of "%s". But it returns %s', Client::class, is_object($client) ? $client::class : gettype($client)));
+ }
+
+ $this->clients[] = $client;
+
+ return $client;
+ }
+}
diff --git a/pkg/wamp/WampDestination.php b/pkg/wamp/WampDestination.php
new file mode 100644
index 000000000..a99bc1fa0
--- /dev/null
+++ b/pkg/wamp/WampDestination.php
@@ -0,0 +1,31 @@
+name = $name;
+ }
+
+ public function getQueueName(): string
+ {
+ return $this->name;
+ }
+
+ public function getTopicName(): string
+ {
+ return $this->name;
+ }
+}
diff --git a/pkg/wamp/WampMessage.php b/pkg/wamp/WampMessage.php
new file mode 100644
index 000000000..9ad41f5a4
--- /dev/null
+++ b/pkg/wamp/WampMessage.php
@@ -0,0 +1,21 @@
+body = $body;
+ $this->properties = $properties;
+ $this->headers = $headers;
+ $this->redelivered = false;
+ }
+}
diff --git a/pkg/wamp/WampProducer.php b/pkg/wamp/WampProducer.php
new file mode 100644
index 000000000..71ea625ae
--- /dev/null
+++ b/pkg/wamp/WampProducer.php
@@ -0,0 +1,182 @@
+context = $context;
+ }
+
+ /**
+ * @param WampDestination $destination
+ * @param WampMessage $message
+ */
+ public function send(Destination $destination, Message $message): void
+ {
+ InvalidDestinationException::assertDestinationInstanceOf($destination, WampDestination::class);
+ InvalidMessageException::assertMessageInstanceOf($message, WampMessage::class);
+
+ $init = false;
+ $this->message = $message;
+ $this->destination = $destination;
+
+ if (null === $this->client) {
+ $init = true;
+
+ $this->client = $this->context->getNewClient();
+ $this->client->setAttemptRetry(true);
+ $this->client->on('open', function (ClientSession $session) {
+ $this->session = $session;
+
+ $this->doSendMessageIfPossible();
+ });
+
+ $this->client->on('close', function () {
+ if ($this->session === $this->client->getSession()) {
+ $this->session = null;
+ }
+ });
+
+ $this->client->on('error', function () {
+ if ($this->session === $this->client->getSession()) {
+ $this->session = null;
+ }
+ });
+
+ $this->client->on('do-send', function (WampDestination $destination, WampMessage $message) {
+ $onFinish = function () {
+ $this->client->emit('do-stop');
+ };
+
+ $payload = $this->context->getSerializer()->toString($message);
+
+ $this->session->publish($destination->getTopicName(), [$payload], [], ['acknowledge' => true])
+ ->then($onFinish, $onFinish);
+ });
+
+ $this->client->on('do-stop', function () {
+ $this->client->getLoop()->stop();
+ });
+ }
+
+ $this->client->getLoop()->futureTick(function () {
+ $this->doSendMessageIfPossible();
+ });
+
+ if ($init) {
+ $this->client->start(false);
+ }
+
+ $this->client->getLoop()->run();
+ }
+
+ /**
+ * @return WampProducer
+ */
+ public function setDeliveryDelay(?int $deliveryDelay = null): Producer
+ {
+ if (null === $deliveryDelay) {
+ return $this;
+ }
+
+ throw DeliveryDelayNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function getDeliveryDelay(): ?int
+ {
+ return null;
+ }
+
+ /**
+ * @return WampProducer
+ */
+ public function setPriority(?int $priority = null): Producer
+ {
+ if (null === $priority) {
+ return $this;
+ }
+
+ throw PriorityNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function getPriority(): ?int
+ {
+ return null;
+ }
+
+ /**
+ * @return WampProducer
+ */
+ public function setTimeToLive(?int $timeToLive = null): Producer
+ {
+ if (null === $timeToLive) {
+ return $this;
+ }
+
+ throw TimeToLiveNotSupportedException::providerDoestNotSupportIt();
+ }
+
+ public function getTimeToLive(): ?int
+ {
+ return null;
+ }
+
+ private function doSendMessageIfPossible()
+ {
+ if (null === $this->session) {
+ return;
+ }
+
+ if (null === $this->message) {
+ return;
+ }
+
+ $message = $this->message;
+ $destination = $this->destination;
+
+ $this->message = null;
+ $this->destination = null;
+
+ $this->client->emit('do-send', [$destination, $message]);
+ }
+}
diff --git a/pkg/wamp/WampSubscriptionConsumer.php b/pkg/wamp/WampSubscriptionConsumer.php
new file mode 100644
index 000000000..2d25a673b
--- /dev/null
+++ b/pkg/wamp/WampSubscriptionConsumer.php
@@ -0,0 +1,161 @@
+context = $context;
+ $this->subscribers = [];
+ }
+
+ public function getClient(): ?Client
+ {
+ return $this->client;
+ }
+
+ public function consume(int $timeout = 0): void
+ {
+ if (empty($this->subscribers)) {
+ throw new \LogicException('There is no subscribers. Consider calling basicConsumeSubscribe before consuming');
+ }
+
+ $init = false;
+
+ if (null === $this->client) {
+ $init = true;
+
+ $this->client = $this->context->getNewClient();
+ $this->client->setAttemptRetry(true);
+ $this->client->on('open', function (ClientSession $session) {
+ foreach ($this->subscribers as $queue => $subscriber) {
+ $session->subscribe($queue, function ($args) use ($subscriber) {
+ $message = $this->context->getSerializer()->toMessage($args[0]);
+
+ /** @var WampConsumer $consumer */
+ /** @var callable $callback */
+ list($consumer, $callback) = $subscriber;
+
+ if (false === call_user_func($callback, $message, $consumer)) {
+ $this->client->emit('do-stop');
+ }
+ });
+ }
+ });
+
+ $this->client->on('do-stop', function () {
+ if ($this->timer) {
+ $this->client->getLoop()->cancelTimer($this->timer);
+ }
+
+ $this->client->getLoop()->stop();
+ });
+ }
+
+ if ($timeout > 0) {
+ $timeout /= 1000;
+ $timeout = $timeout >= 0.1 ? $timeout : 0.1;
+
+ $this->timer = $this->client->getLoop()->addTimer($timeout, function () {
+ $this->client->emit('do-stop');
+ });
+ }
+
+ if ($init) {
+ $this->client->start(false);
+ }
+
+ $this->client->getLoop()->run();
+ }
+
+ /**
+ * @param WampConsumer $consumer
+ */
+ public function subscribe(Consumer $consumer, callable $callback): void
+ {
+ if (false == $consumer instanceof WampConsumer) {
+ throw new \InvalidArgumentException(sprintf('The consumer must be instance of "%s" got "%s"', WampConsumer::class, $consumer::class));
+ }
+
+ if ($this->client) {
+ throw new \LogicException('Could not subscribe after consume was called');
+ }
+
+ $queueName = $consumer->getQueue()->getQueueName();
+ if (array_key_exists($queueName, $this->subscribers)) {
+ if ($this->subscribers[$queueName][0] === $consumer && $this->subscribers[$queueName][1] === $callback) {
+ return;
+ }
+
+ throw new \InvalidArgumentException(sprintf('There is a consumer subscribed to queue: "%s"', $queueName));
+ }
+
+ $this->subscribers[$queueName] = [$consumer, $callback];
+ }
+
+ /**
+ * @param WampConsumer $consumer
+ */
+ public function unsubscribe(Consumer $consumer): void
+ {
+ if (false == $consumer instanceof WampConsumer) {
+ throw new \InvalidArgumentException(sprintf('The consumer must be instance of "%s" got "%s"', WampConsumer::class, $consumer::class));
+ }
+
+ if ($this->client) {
+ throw new \LogicException('Could not unsubscribe after consume was called');
+ }
+
+ $queueName = $consumer->getQueue()->getQueueName();
+
+ if (false == array_key_exists($queueName, $this->subscribers)) {
+ return;
+ }
+
+ if ($this->subscribers[$queueName][0] !== $consumer) {
+ return;
+ }
+
+ unset($this->subscribers[$queueName]);
+ }
+
+ public function unsubscribeAll(): void
+ {
+ if ($this->client) {
+ throw new \LogicException('Could not unsubscribe after consume was called');
+ }
+
+ $this->subscribers = [];
+ }
+}
diff --git a/pkg/wamp/composer.json b/pkg/wamp/composer.json
new file mode 100644
index 000000000..3d260254f
--- /dev/null
+++ b/pkg/wamp/composer.json
@@ -0,0 +1,49 @@
+{
+ "name": "enqueue/wamp",
+ "type": "library",
+ "description": "The Web Application Messaging Protocol Transport",
+ "keywords": ["messaging", "queue", "wamp", "thruway"],
+ "homepage": "https://enqueue.forma-pro.com/",
+ "license": "MIT",
+ "require": {
+ "php": "^8.1",
+ "queue-interop/queue-interop": "^0.8.1",
+ "enqueue/dsn": "^0.10.8",
+ "thruway/client": "^0.5.5",
+ "thruway/pawl-transport": "^0.5.2",
+ "voryx/thruway-common": "^1.0.1",
+ "ratchet/pawl": "^0.4.3",
+ "ratchet/rfc6455": "^0.4.0",
+ "react/dns": "^1.4",
+ "react/event-loop": "^1.2",
+ "react/promise": "^2.8"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^9.5",
+ "enqueue/test": "0.10.x-dev",
+ "enqueue/null": "0.10.x-dev",
+ "queue-interop/queue-spec": "^0.6.2"
+ },
+ "support": {
+ "email": "opensource@forma-pro.com",
+ "issues": "https://github.com/php-enqueue/enqueue-dev/issues",
+ "forum": "https://gitter.im/php-enqueue/Lobby",
+ "source": "https://github.com/php-enqueue/enqueue-dev",
+ "docs": "https://github.com/php-enqueue/enqueue-dev/blob/master/docs/index.md"
+ },
+ "autoload": {
+ "psr-4": { "Enqueue\\Wamp\\": "" },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "minimum-stability": "beta",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "0.10.x-dev"
+ }
+ },
+ "config": {
+ "prefer-stable": true
+ }
+}
diff --git a/pkg/wamp/phpunit.xml.dist b/pkg/wamp/phpunit.xml.dist
new file mode 100644
index 000000000..9e8558ce8
--- /dev/null
+++ b/pkg/wamp/phpunit.xml.dist
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+ ./Tests
+
+
+
+
+
+ .
+
+ ./vendor
+ ./Tests
+
+
+
+
diff --git a/var/rabbitmq_certificates/cert.pem b/var/rabbitmq_certificates/cert.pem
index 8626b0ca5..12b395936 100644
--- a/var/rabbitmq_certificates/cert.pem
+++ b/var/rabbitmq_certificates/cert.pem
@@ -1,18 +1,18 @@
-----BEGIN CERTIFICATE-----
-MIIC5TCCAc2gAwIBAgIBAjANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAhNeVRl
-c3RDQTAeFw0xNzExMDExMzE1NDBaFw0xODExMDExMzE1NDBaMCgxFTATBgNVBAMM
-DGNiNzA0YmRhYWZjNjEPMA0GA1UECgwGY2xpZW50MIIBIjANBgkqhkiG9w0BAQEF
-AAOCAQ8AMIIBCgKCAQEAxLvg5RmUO3Ws+9D0Xh1l0k5Hg30jUWcyV4nCX2wJgxz5
-mjApsEYqSytE3Sr63Otl+yUugoL8gPdO7eWslWJycIWKFEWOmE7G3V89kjAd/sNP
-U6Wo2j4T9pCRLogOuq54SPEEdn2HGPr+JaUYRvdsXZmLy6Wa1dnx3UemxKirKpmo
-uxkqTfycZFKq8RQsOrMqMtZFExgN++ylNMDcl7rYG3cYduKN9uBq5Fwcl5oan76f
-NvTnW++bolSOVa6wKTfPt9a+XcsAxx+XSrWx17HaegrTFMizFxTWOwqfNVCTmJkD
-rI4GYoat1ymHlb5v0MQRaMSWi+USLmrKIEUqXbwHJwIDAQABoy8wLTAJBgNVHRME
+MIIC5TCCAc2gAwIBAgIBBDANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAhNeVRl
+c3RDQTAeFw0xODExMDUxMDMyMjdaFw0yODExMDIxMDMyMjdaMCgxFTATBgNVBAMM
+DDE4OGUzNGFjNWQ4MTEPMA0GA1UECgwGY2xpZW50MIIBIjANBgkqhkiG9w0BAQEF
+AAOCAQ8AMIIBCgKCAQEA2pgaF9Dk7YtbE2/LJKnpDzwTeSWuvplVuysNW70P1AiD
+9LMplvkYG1Jbmr8Tfd15LkkZi/IQroISuqFhol0IvflFT8t1Q5O/9rGFpRLujyiI
+bidBaTszFNFPNjhPGyyw2eEQEHNzeAFpOdA0kWdYap3OI7DDdleU8SOLt4bLlwoD
+ZC9S2RSpycFJL7JzfnjwkvtH3GVH2WYCukFYJsQGpQ/LbCHZ5ut+2cvM4BeKPH2B
+YdfCRrrPsRxO9GDh1SW1uMaX4d4AsyM5twh+GCPMBDu5dQh4d7hqxN4hcqFr7mzp
+m5H84x3CrAnuDo6Q8vyVv/3VzxnobptCz3nksQxIRQIDAQABoy8wLTAJBgNVHRME
AjAAMAsGA1UdDwQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAjANBgkqhkiG9w0B
-AQsFAAOCAQEAhudxAnKUKXzlO2AvNYR561T9u1jTtIirInbMGPH4oVqcRyC47PeX
-vrURQg5d1VOw4Sb1Ul+sM4ur4PLt990TsOt3NZiuEeam37Ra3oyxu+9XVobxOGnV
-a/6mozFZGRcOzsbdX46DZtAl5NVJm5M1nHPNg1KqGZF+AVwTOPvPMWpn+IzckEHD
-N/4jxM6FCzc5QRQKkyEOTQz848V0HDlXB9KSwgSIQ8yUXv2ozMeqxq6J+oXpzhb9
-wT2YUIGr9thoB7CwWjnFgG7MEXQ3wk1L1SzRz57a3r+rBIMHBNEkakAoq9VmzKLA
-y6xpRqt0+CnvmQ9OIdY4jxUMVXxcQGjUnw==
+AQsFAAOCAQEA16hw/R7sZ5d0ykwKFzcjYSN+Dl8mnka1PRfVGqxFluahytbvD3Ns
+yzhdXD4iaTumuVqjyOSe7WfA4hE1Nb1aW2H6GhEzqDsFo/usmC6H6zH9HXVtI9wM
+l7sa7THWh1BTNssRBtihpjhjlWzU6eQd7F7O3rhPoM0FeZ7S78ZCo8R86p72xaKg
+Ttx+CNfUyvDEY35Jh5kYg/VW0V1/M6zsif0xEbSYTmEkirS4exdrk8Hy5q70V8ZN
+UEHxXOcQRN+Y+SP8xFUWNjpRO/+P+ZapvXUd47FnZ12Hxyp9V+V1yqO24mv4RzpO
+AMpTn8botOTbuvQXqzr398uOwxZ7RlTzIg==
-----END CERTIFICATE-----
diff --git a/var/rabbitmq_certificates/key.pem b/var/rabbitmq_certificates/key.pem
index cc4315e85..8ec88ecd8 100644
--- a/var/rabbitmq_certificates/key.pem
+++ b/var/rabbitmq_certificates/key.pem
@@ -1,27 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
-MIIEpQIBAAKCAQEAxLvg5RmUO3Ws+9D0Xh1l0k5Hg30jUWcyV4nCX2wJgxz5mjAp
-sEYqSytE3Sr63Otl+yUugoL8gPdO7eWslWJycIWKFEWOmE7G3V89kjAd/sNPU6Wo
-2j4T9pCRLogOuq54SPEEdn2HGPr+JaUYRvdsXZmLy6Wa1dnx3UemxKirKpmouxkq
-TfycZFKq8RQsOrMqMtZFExgN++ylNMDcl7rYG3cYduKN9uBq5Fwcl5oan76fNvTn
-W++bolSOVa6wKTfPt9a+XcsAxx+XSrWx17HaegrTFMizFxTWOwqfNVCTmJkDrI4G
-Yoat1ymHlb5v0MQRaMSWi+USLmrKIEUqXbwHJwIDAQABAoIBAQCwhbPBXTY4M9pH
-CLJ7T/1wunRIcxwhimsNSLpzTEksr+72foipdgu07toXaN03JLCYrEATMtzGCyFz
-LEWytGbit6+xiMftuaGOOErSxQHk+fJPp7DeQh0/e3AJRGOS9cFQEZJjjzaNH4iy
-1nP2GUPOqFtbGvjXMXtnhUcJ5h3PVgViKf/uRjk2PH6NGgZZy1kGpCHZkNX5W0r1
-cc5TXc5luVsnBPwvLbeg08Pan8+Z1HbYv+nkZtosM32nbwcw1go42RYNAcvKmojI
-+lw97SdLaz7WQHu35or3vIR+6xBSLL0wKdnwNuf91WSCDn+KDckTDbg8O8t221ok
-AwGMtVQBAoGBAOwr4oqnJ1DrqQod0OA1kQODUZGjte+QFU2be0UrIkw6b8FdoE7z
-J23luNezl/Omq6d1g7QOsyTt9MesY/WDiLahmGG+uviNkW3IusB3jBx69oXzJHbg
-Chkd1/TBjdcllQkZfnPh50NWhsxKCgt/eM/FfsgntaqlFryxrHzWlUSnAoGBANVA
-WVriK4M+5MeHdUtXeczAj7jBnet1gBSR4pPmya4vq543BLEgV7Pha4rDAsCFQTdC
-JyDKG2+amDBH0vIX4NGFZhZh5/WkgCoDzb+xW/afn5EgLobiNaa1wyWfUIFKDcAu
-n1BbHBkJn7V26Z5syNkvr2yEc+lcrz59SeQfEvmBAoGBAJLmCRctOWs/6fj86rtL
-FlQVDluEdNn5yQZou5geaEr53iFsVxZEcDYPOZYRg2ZuOT8D/VO2AP/rcuHv/Izt
-r8/JW7sQo8OOavLadC7bLS9Z3JUc04WNfTp6MaVv7wXvvm/Wh60UyoA8BcR0GSNl
-uoOh2GYvLPRjk2zzJtLPtjDpAoGAbqYt9wdFlpsKsDEr/kTMUR5VNINaAnN8Wq/7
-hcyJNxVLEhPwHkvu1coQN/bJtcUuupJbpRrZM4ZekyahYLZdE7oI53IznnSVf7dr
-iZxoYEYg0HeHTLuRJQhI0nuglQUsr1xBk7tCkAc7VDf4Lhi5+l9QwZjUX/CUiXMO
-5Qvul4ECgYEAu3yPmw+kl1bQP7mmWjY9aYgUL3CBXNlBA9n51AXHXWYU0/SdnvAT
-vk/dg/cjyoZyopU/sRceiFkFq7YAnDNGBucCsmEAFTbc9ildtlJNDkbtzAQ2c4OG
-0ikLlJLApyvcTGZu7iWjyVe2vdUlECjvqmSTA5uTNn4icJBj/Or4W5I=
+MIIEowIBAAKCAQEA2pgaF9Dk7YtbE2/LJKnpDzwTeSWuvplVuysNW70P1AiD9LMp
+lvkYG1Jbmr8Tfd15LkkZi/IQroISuqFhol0IvflFT8t1Q5O/9rGFpRLujyiIbidB
+aTszFNFPNjhPGyyw2eEQEHNzeAFpOdA0kWdYap3OI7DDdleU8SOLt4bLlwoDZC9S
+2RSpycFJL7JzfnjwkvtH3GVH2WYCukFYJsQGpQ/LbCHZ5ut+2cvM4BeKPH2BYdfC
+RrrPsRxO9GDh1SW1uMaX4d4AsyM5twh+GCPMBDu5dQh4d7hqxN4hcqFr7mzpm5H8
+4x3CrAnuDo6Q8vyVv/3VzxnobptCz3nksQxIRQIDAQABAoIBAFPcAjacxxZyXdBJ
+FQ/Nt0FG9NmHIVCxlnglfgxxrX7UfXsEuLHYge0JXWcyYpHowzKEjK5pgQjRkcnT
+W5dkRZRL6tE/5o60QfKsC+9WIfr9u8k2ehuawG/+FHtigsaUEIylkPoesG+bavjo
+7SHTGdJdE9YRXAssclFIJ7OSnMwmL6Q3l4KbZd4Gwz7h16kT3tiW1djI+Dt3POiX
+14/3HDXq69eoYwvpGuxyU4K2e9GpiCmYspF1rt9s9row2OUjYevl3Mdr/3YjiDo7
+U9NCDVhzl2AfxpfFI9EMHAQuUQYb1lU4L4OCmEUs20ZjfYSSTrl4vDNumOgi0sDX
+snZKJsECgYEA9R01tSi4j+BmcZK1UPgxRyvCxen087j0hfn5GoqlF0z85RFgseIu
+hZ6jKWZtrUHN7yOIogUwyYRHDtIe/xChTdp/fFw56qQfIKR7pqScw+X/GglMLbRc
+2qjnT8/imxaE2mfghnJ1Ts0Elc4ZW7H2W8up18LutKDCX/McuaqXstkCgYEA5E1g
+lK+ToUI9HiN2uYl7Xhda5gVuLhTsKIFuIxjyhL8lg+hN/SYIRbldOD8YhH6nPnkx
+qDofvUJw9GMaCsigwzBzNbKOiB4tZKBkavbrXFHKLU1R4ZDLtqgxlFtDYBTt+xyn
+54GEwZV0FNVK/mRRRq8yWpTTXhflCN0xvO+PRU0CgYAKJKNMU9sPWSHkIUYPi7W+
+VDlDJ2NTkpvLz4RXbNVYGX99mzJ9Kfby4JWv6OUw/kAfXUESM1TJggfOvTM7Kt0B
+88DCzK4434HKQAQ96SHzmVjtIuVcHtKY2dR4oQmnkU7+Gr5X0fS4xhMif9zcxoiD
+U/I7U329S8m/XrgZls2gQQKBgB4a3ft9U5hWJb0NrCA3Mt9rcP8YBDlrZODKgH18
+Uq6Sjh3gyjfxhfG7ycEbAN6n3OHuFVA7qefJFSAE2XBGmHxkrSyNiSIF6LJ2PAem
+285msqRap8t4zoQdlbwcdLv8xozwcGuktp7YWGBO5/63t8f8XkV3jo+/0uHiWSay
+6E+ZAoGBAOk0eYTLurIylLQH0uEuy55wY4u79mb2ukFSQqa6iXU55ZExXd8Dphqu
+nDy1NuxoCR8fbfhtr7Ea0RhKJJKqBNhK6r48ZgYsSwFsXPDvlAstnT7ZYe2tyszg
+HBby3tmlpiNLFrR9e7RMpWxB+7Myu8bWPbLI1WcbbLkTbA63XKqy
-----END RSA PRIVATE KEY-----