diff --git a/.travis.yml b/.travis.yml index f358a00cf..ecc11eaf0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,6 +20,12 @@ matrix: - php: 7.2 sudo: false env: SYMFONY_VERSION=4.0.* UNIT_TESTS=true + - php: 7.3 + sudo: false + env: SYMFONY_VERSION=4.1.* UNIT_TESTS=true + - php: 7.3 + sudo: false + env: SYMFONY_VERSION=4.2.* UNIT_TESTS=true - php: 7.1 services: docker sudo: required diff --git a/CHANGELOG.md b/CHANGELOG.md index b5f026489..cc4f53ec6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Change Log +## [0.9.10](https://github.com/php-enqueue/enqueue-dev/tree/0.9.10) (2019-05-14) +[Full Changelog](https://github.com/php-enqueue/enqueue-dev/compare/0.9.9...0.9.10) + +**Merged pull requests:** + +- \[client\] Lazy producer. [\#845](https://github.com/php-enqueue/enqueue-dev/pull/845) ([makasim](https://github.com/makasim)) +- \[kafka\] Fix consumption errors in kafka against recent versions in librdkafka/phprdkafka [\#842](https://github.com/php-enqueue/enqueue-dev/pull/842) ([Steveb-p](https://github.com/Steveb-p)) +- \[amqp-lib\] Fix un-initialized property use [\#836](https://github.com/php-enqueue/enqueue-dev/pull/836) ([Steveb-p](https://github.com/Steveb-p)) +- \[amqp-bunny\] Fix heartbeat configuration in bunny with 0 \(off\) value [\#820](https://github.com/php-enqueue/enqueue-dev/pull/820) ([nightlinus](https://github.com/nightlinus)) +- \[stomp\] Add support for using the /topic prefix instead of /exchange. [\#826](https://github.com/php-enqueue/enqueue-dev/pull/826) ([alessandroniciforo](https://github.com/alessandroniciforo)) +- \[sns\] Allow setting SNS message attributes, other fields [\#799](https://github.com/php-enqueue/enqueue-dev/pull/799) ([aldenw](https://github.com/aldenw)) +- Fixed docs [\#822](https://github.com/php-enqueue/enqueue-dev/pull/822) ([Toflar](https://github.com/Toflar)) +- Typo on the tag [\#818](https://github.com/php-enqueue/enqueue-dev/pull/818) ([appeltaert](https://github.com/appeltaert)) + ## [0.9.9](https://github.com/php-enqueue/enqueue-dev/tree/0.9.9) (2019-04-04) [Full Changelog](https://github.com/php-enqueue/enqueue-dev/compare/0.9.8...0.9.9) diff --git a/composer.json b/composer.json index 639b274b6..cb9751df8 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,6 @@ "ramsey/uuid": "^2|^3.5", "psr/log": "^1", "psr/container": "^1", - "symfony/event-dispatcher": "4.0.*", "makasim/temp-file": "^0.2", "google/cloud-pubsub": "^0.6.1|^1.0", "doctrine/orm": "~2.4", @@ -40,16 +39,16 @@ "phpunit/phpunit": "^5.5", "phpstan/phpstan": "^0.10", "queue-interop/queue-spec": "^0.6", - "symfony/browser-kit": "4.0.*", - "symfony/config": "4.0.*", - "symfony/process": "4.0.*", - "symfony/console": "4.0.*", - "symfony/dependency-injection": "4.0.*", - "symfony/event-dispatcher": "4.0.*", - "symfony/expression-language": "4.0.*", - "symfony/http-kernel": "4.0.*", - "symfony/filesystem": "4.0.*", - "symfony/framework-bundle": "4.0.*", + "symfony/browser-kit": "^3.4|^4", + "symfony/config": "^3.4|^4", + "symfony/process": "^3.4|^4", + "symfony/console": "^3.4|^4", + "symfony/dependency-injection": "^3.4|^4", + "symfony/event-dispatcher": "^3.4|^4", + "symfony/expression-language": "^3.4|^4", + "symfony/http-kernel": "^3.4|^4", + "symfony/filesystem": "^3.4|^4", + "symfony/framework-bundle": "^3.4|^4", "empi89/php-amqp-stubs": "*@dev", "doctrine/doctrine-bundle": "~1.2", "kwn/php-rdkafka-stubs": "^1.0.2", diff --git a/docs/client/extensions.md b/docs/client/extensions.md index 19f40fc78..979d13d60 100644 --- a/docs/client/extensions.md +++ b/docs/client/extensions.md @@ -46,7 +46,7 @@ services: timestamp_message_extension: class: Acme\TimestampMessageExtension tags: - - { name: 'enqueue.client.extensions' } + - { name: 'enqueue.client.extension' } ``` You can add `priority` attribute with a number. The higher value you set the earlier the extension is called. diff --git a/docs/transport/stomp.md b/docs/transport/stomp.md index c7b460dc5..d5cc79868 100644 --- a/docs/transport/stomp.md +++ b/docs/transport/stomp.md @@ -36,6 +36,12 @@ $factory = new StompConnectionFactory('stomp:'); // same as above $factory = new StompConnectionFactory([]); +// connect via stomp to RabbitMQ (default) - the topic names are prefixed with /exchange +$factory = new StompConnectionFactory('stomp+rabbitmq:'); + +// connect via stomp to ActiveMQ - the topic names are prefixed with /topic +$factory = new StompConnectionFactory('stomp+activemq:'); + // connect to stomp broker at example.com port 1000 using $factory = new StompConnectionFactory([ 'host' => 'example.com', diff --git a/pkg/amqp-bunny/AmqpConnectionFactory.php b/pkg/amqp-bunny/AmqpConnectionFactory.php index 241929abe..ca56d428c 100644 --- a/pkg/amqp-bunny/AmqpConnectionFactory.php +++ b/pkg/amqp-bunny/AmqpConnectionFactory.php @@ -87,6 +87,7 @@ private function establishConnection(): BunnyClient $bunnyConfig['password'] = $this->config->getPass(); $bunnyConfig['read_write_timeout'] = min($this->config->getReadTimeout(), $this->config->getWriteTimeout()); $bunnyConfig['timeout'] = $this->config->getConnectionTimeout(); + $bunnyConfig['heartbeat'] = $this->config->getHeartbeat(); // @see https://github.com/php-enqueue/enqueue-dev/issues/229 // $bunnyConfig['persistent'] = $this->config->isPersisted(); @@ -94,10 +95,6 @@ private function establishConnection(): BunnyClient // $bunnyConfig['path'] = 'enqueue';//$this->config->getOption('path', $this->config->getOption('vhost')); // } - if ($this->config->getHeartbeat()) { - $bunnyConfig['heartbeat'] = $this->config->getHeartbeat(); - } - if (null !== $this->config->getOption('tcp_nodelay')) { $bunnyConfig['tcp_nodelay'] = $this->config->getOption('tcp_nodelay'); } diff --git a/pkg/amqp-lib/AmqpSubscriptionConsumer.php b/pkg/amqp-lib/AmqpSubscriptionConsumer.php index 694c134dc..a5917dbed 100644 --- a/pkg/amqp-lib/AmqpSubscriptionConsumer.php +++ b/pkg/amqp-lib/AmqpSubscriptionConsumer.php @@ -34,6 +34,7 @@ class AmqpSubscriptionConsumer implements InteropAmqpSubscriptionConsumer public function __construct(AmqpContext $context, bool $heartbeatOnTick) { + $this->subscribers = []; $this->context = $context; $this->heartbeatOnTick = $heartbeatOnTick; } 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 eab956cc4..eda14e00c 100644 --- a/pkg/enqueue-bundle/Tests/Functional/App/config/custom-config.yml +++ b/pkg/enqueue-bundle/Tests/Functional/App/config/custom-config.yml @@ -31,6 +31,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 diff --git a/pkg/enqueue-bundle/Tests/Functional/LazyProducerTest.php b/pkg/enqueue-bundle/Tests/Functional/LazyProducerTest.php new file mode 100644 index 000000000..cf9af030e --- /dev/null +++ b/pkg/enqueue-bundle/Tests/Functional/LazyProducerTest.php @@ -0,0 +1,79 @@ +remove(static::$kernel->getLogDir()); + $fs->remove(static::$kernel->getCacheDir()); + } + + parent::tearDown(); + } + + public function testShouldAllowGetLazyProducerWithoutError() + { + $this->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'); + } + + /** + * @return string + */ + public static function getKernelClass() + { + 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/UseCasesTest.php b/pkg/enqueue-bundle/Tests/Functional/UseCasesTest.php index 0a5f38325..f4f11abb1 100644 --- a/pkg/enqueue-bundle/Tests/Functional/UseCasesTest.php +++ b/pkg/enqueue-bundle/Tests/Functional/UseCasesTest.php @@ -372,9 +372,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..2b4f58173 100644 --- a/pkg/enqueue-bundle/Tests/Functional/WebTestCase.php +++ b/pkg/enqueue-bundle/Tests/Functional/WebTestCase.php @@ -13,7 +13,7 @@ abstract class WebTestCase extends BaseWebTestCase /** * @var Client */ - protected $client; + protected static $client; /** * @var ContainerInterface @@ -25,18 +25,21 @@ protected function setUp() 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(); } + protected function tearDown() + { + static::$client = null; + static::$kernel = null; + static::$container = null; + } + /** * @return string */ diff --git a/pkg/enqueue/Symfony/Client/DependencyInjection/ClientFactory.php b/pkg/enqueue/Symfony/Client/DependencyInjection/ClientFactory.php index e69311e36..bdae6f3b5 100644 --- a/pkg/enqueue/Symfony/Client/DependencyInjection/ClientFactory.php +++ b/pkg/enqueue/Symfony/Client/DependencyInjection/ClientFactory.php @@ -21,12 +21,14 @@ use Enqueue\Consumption\QueueConsumer; use Enqueue\Rpc\RpcFactory; use Enqueue\Symfony\Client\FlushSpoolProducerListener; +use Enqueue\Symfony\Client\LazyProducer; use Enqueue\Symfony\ContainerProcessorRegistry; use Enqueue\Symfony\DependencyInjection\TransportFactory; use Enqueue\Symfony\DiUtils; use Interop\Queue\Context; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\NodeDefinition; +use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Reference; @@ -119,14 +121,21 @@ public function build(ContainerBuilder $container, array $config): void ; $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('producer')) + ->addArgument($this->diUtils->reference('lazy_producer')) ; $container->register($this->diUtils->format('client_extensions'), ChainExtension::class) @@ -200,12 +209,12 @@ public function build(ContainerBuilder $container, array $config): void $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('producer'), + $this->diUtils->format('producer') => $this->diUtils->reference('lazy_producer'), ])); } if ($this->default) { - $container->setAlias(ProducerInterface::class, $this->diUtils->format('producer')); + $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()) { 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/DependencyInjection/TransportFactory.php b/pkg/enqueue/Symfony/DependencyInjection/TransportFactory.php index 5cc1a6507..54dba4bf7 100644 --- a/pkg/enqueue/Symfony/DependencyInjection/TransportFactory.php +++ b/pkg/enqueue/Symfony/DependencyInjection/TransportFactory.php @@ -117,7 +117,7 @@ public static function getQueueConsumerConfiguration(string $name = 'consumption ->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() ; diff --git a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRegistryPassTest.php b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRegistryPassTest.php index c0142f0e3..4d95ca07d 100644 --- a/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRegistryPassTest.php +++ b/pkg/enqueue/Tests/Symfony/Client/DependencyInjection/BuildProcessorRegistryPassTest.php @@ -136,10 +136,10 @@ private function assertLocatorServices(ContainerBuilder $container, $locatorId, $locatorId = (string) $locatorId; $this->assertTrue($container->hasDefinition($locatorId)); - $this->assertRegExp('/service_locator\..*?\.enqueue\./', $locatorId); + $this->assertRegExp('/\.?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/BuildProcessorRegistryPassTest.php b/pkg/enqueue/Tests/Symfony/DependencyInjection/BuildProcessorRegistryPassTest.php index d122e044c..989d048cf 100644 --- a/pkg/enqueue/Tests/Symfony/DependencyInjection/BuildProcessorRegistryPassTest.php +++ b/pkg/enqueue/Tests/Symfony/DependencyInjection/BuildProcessorRegistryPassTest.php @@ -199,10 +199,10 @@ private function assertLocatorServices(ContainerBuilder $container, $locatorId, $locatorId = (string) $locatorId; $this->assertTrue($container->hasDefinition($locatorId)); - $this->assertRegExp('/service_locator\..*?\.enqueue\./', $locatorId); + $this->assertRegExp('/\.?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/LazyProducerTest.php b/pkg/enqueue/Tests/Symfony/LazyProducerTest.php new file mode 100644 index 000000000..b574414c7 --- /dev/null +++ b/pkg/enqueue/Tests/Symfony/LazyProducerTest.php @@ -0,0 +1,133 @@ +assertClassImplements(ProducerInterface::class, LazyProducer::class); + } + + public function testCouldBeConstructedWithContainerAndServiceId() + { + new LazyProducer($this->createContainerMock(), 'realProducerId'); + } + + 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/job-queue/Tests/Functional/WebTestCase.php b/pkg/job-queue/Tests/Functional/WebTestCase.php index 329762004..ecb6e5af9 100644 --- a/pkg/job-queue/Tests/Functional/WebTestCase.php +++ b/pkg/job-queue/Tests/Functional/WebTestCase.php @@ -11,7 +11,7 @@ abstract class WebTestCase extends BaseWebTestCase /** * @var Client */ - protected $client; + protected static $client; /** * @var ContainerInterface @@ -24,7 +24,7 @@ protected function setUp() static::$class = null; - $this->client = static::createClient(); + static::$client = static::createClient(); if (false == static::$container) { static::$container = static::$kernel->getContainer(); diff --git a/pkg/rdkafka/RdKafkaConsumer.php b/pkg/rdkafka/RdKafkaConsumer.php index 9522b32ee..d7016a946 100644 --- a/pkg/rdkafka/RdKafkaConsumer.php +++ b/pkg/rdkafka/RdKafkaConsumer.php @@ -155,6 +155,10 @@ 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: diff --git a/pkg/sns/SnsMessage.php b/pkg/sns/SnsMessage.php index 7eb3c0d83..f7311d0b0 100644 --- a/pkg/sns/SnsMessage.php +++ b/pkg/sns/SnsMessage.php @@ -6,28 +6,218 @@ use Interop\Queue\Impl\MessageTrait; use Interop\Queue\Message; +use Psr\Http\Message\StreamInterface; class SnsMessage implements Message { use MessageTrait; + /** + * @var string|null + */ private $snsMessageId; - public function __construct(string $body = '', array $properties = [], array $headers = []) - { + /** + * @var string|null + */ + private $messageStructure; + + /** + * @var string|null + */ + private $phoneNumber; + + /** + * @var string|null + */ + private $subject; + + /** + * @var array|null + */ + private $messageAttributes; + + /** + * @var string|null + */ + private $targetArn; + + /** + * SnsMessage constructor. + * + * See AWS documentation for message attribute structure. + * + * @see https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sns-2010-03-31.html#shape-messageattributevalue + * + * @param string $body + * @param array $properties + * @param array $headers + * @param array|null $messageAttributes + * @param string|null $messageStructure + * @param string|null $phoneNumber + * @param string|null $subject + * @param string|null $targetArn + */ + public function __construct( + string $body = '', + array $properties = [], + array $headers = [], + array $messageAttributes = null, + string $messageStructure = null, + string $phoneNumber = null, + string $subject = null, + string $targetArn = null + ) { $this->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; } + /** + * @return string|null + */ public function getSnsMessageId(): ?string { return $this->snsMessageId; } + /** + * @param string|null $snsMessageId + */ public function setSnsMessageId(?string $snsMessageId): void { $this->snsMessageId = $snsMessageId; } + + /** + * @return string|null + */ + public function getMessageStructure(): ?string + { + return $this->messageStructure; + } + + /** + * @param string|null $messageStructure + */ + public function setMessageStructure(?string $messageStructure): void + { + $this->messageStructure = $messageStructure; + } + + /** + * @return string|null + */ + public function getPhoneNumber(): ?string + { + return $this->phoneNumber; + } + + /** + * @param string|null $phoneNumber + */ + public function setPhoneNumber(?string $phoneNumber): void + { + $this->phoneNumber = $phoneNumber; + } + + /** + * @return string|null + */ + public function getSubject(): ?string + { + return $this->subject; + } + + /** + * @param string|null $subject + */ + public function setSubject(?string $subject): void + { + $this->subject = $subject; + } + + /** + * @return array|null + */ + public function getMessageAttributes(): ?array + { + return $this->messageAttributes; + } + + /** + * @param array|null $messageAttributes + */ + public function setMessageAttributes(?array $messageAttributes): void + { + $this->messageAttributes = $messageAttributes; + } + + /** + * @param string $name + * @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' => '', + * ]. + * + * @param string $name + * @param array|null $attribute + */ + public function setAttribute(string $name, ?array $attribute): void + { + if (null === $attribute) { + unset($this->messageAttributes[$name]); + } else { + $this->messageAttributes[$name] = $attribute; + } + } + + /** + * @param string $name + * @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, + ]; + } + + /** + * @return string|null + */ + public function getTargetArn(): ?string + { + return $this->targetArn; + } + + /** + * @param string|null $targetArn + */ + public function setTargetArn(?string $targetArn): void + { + $this->targetArn = $targetArn; + } } diff --git a/pkg/sns/SnsProducer.php b/pkg/sns/SnsProducer.php index b702d10c3..7f440c77b 100644 --- a/pkg/sns/SnsProducer.php +++ b/pkg/sns/SnsProducer.php @@ -57,6 +57,26 @@ public function send(Destination $destination, Message $message): void '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; + } + $result = $this->context->getSnsClient()->publish($arguments); if (false == $result->hasKey('MessageId')) { diff --git a/pkg/sns/Tests/SnsProducerTest.php b/pkg/sns/Tests/SnsProducerTest.php index f5a039702..4850b5c1d 100644 --- a/pkg/sns/Tests/SnsProducerTest.php +++ b/pkg/sns/Tests/SnsProducerTest.php @@ -126,6 +126,67 @@ public function testShouldPublish() $producer->send($destination, $message); } + /** + * @throws InvalidMessageException + */ + public function testShouldPublishWithMergedAttributes() + { + $context = $this->createSnsContextMock(); + $client = $this->createSnsClientMock(); + + $context + ->expects($this->once()) + ->method('getSnsClient') + ->will($this->returnValue($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 */ diff --git a/pkg/stomp/StompConnectionFactory.php b/pkg/stomp/StompConnectionFactory.php index c88716308..764145ca2 100644 --- a/pkg/stomp/StompConnectionFactory.php +++ b/pkg/stomp/StompConnectionFactory.php @@ -11,6 +11,9 @@ class StompConnectionFactory implements ConnectionFactory { + const SCHEME_EXT_ACTIVEMQ = 'activemq'; + const SCHEME_EXT_RABBITMQ = 'rabbitmq'; + /** * @var array */ @@ -66,13 +69,15 @@ public function __construct($config = 'stomp:') */ public function createContext(): Context { + $useExchangePrefix = self::SCHEME_EXT_RABBITMQ === $this->config['target'] ? true : false; + if ($this->config['lazy']) { return new StompContext(function () { return $this->establishConnection(); - }); + }, $useExchangePrefix); } - return new StompContext($this->establishConnection()); + return new StompContext($this->establishConnection(), $useExchangePrefix); } private function establishConnection(): BufferedStompClient @@ -103,7 +108,16 @@ private function parseDsn(string $dsn): array throw new \LogicException(sprintf('The given DSN is not supported. Must start with "stomp:".')); } + $schemeExtension = current($dsn->getSchemeExtensions()); + if (false === $schemeExtension) { + $schemeExtension = self::SCHEME_EXT_RABBITMQ; + } + if (self::SCHEME_EXT_ACTIVEMQ !== $schemeExtension && self::SCHEME_EXT_RABBITMQ !== $schemeExtension) { + throw new \LogicException(sprintf('The given DSN is not supported. The scheme extension "%s" provided is invalid. It must be one of "%s" or "%s".', $schemeExtension, self::SCHEME_EXT_ACTIVEMQ, self::SCHEME_EXT_RABBITMQ)); + } + return array_filter(array_replace($dsn->getQuery(), [ + 'target' => $schemeExtension, 'host' => $dsn->getHost(), 'port' => $dsn->getPort(), 'login' => $dsn->getUser(), @@ -120,6 +134,7 @@ private function parseDsn(string $dsn): array private function defaultConfig(): array { return [ + 'target' => self::SCHEME_EXT_RABBITMQ, 'host' => 'localhost', 'port' => 61613, 'login' => 'guest', diff --git a/pkg/stomp/StompContext.php b/pkg/stomp/StompContext.php index e03b11cb6..2824e0b27 100644 --- a/pkg/stomp/StompContext.php +++ b/pkg/stomp/StompContext.php @@ -23,6 +23,11 @@ class StompContext implements Context */ private $stomp; + /** + * @var bool + */ + private $useExchangePrefix; + /** * @var callable */ @@ -30,8 +35,9 @@ class StompContext implements Context /** * @param BufferedStompClient|callable $stomp + * @param bool $useExchangePrefix */ - public function __construct($stomp) + public function __construct($stomp, $useExchangePrefix = true) { if ($stomp instanceof BufferedStompClient) { $this->stomp = $stomp; @@ -40,6 +46,8 @@ public function __construct($stomp) } else { throw new \InvalidArgumentException('The stomp argument must be either BufferedStompClient or callable that return BufferedStompClient.'); } + + $this->useExchangePrefix = $useExchangePrefix; } /** @@ -84,7 +92,7 @@ public function createTopic(string $name): Topic { if (0 !== strpos($name, '/')) { $destination = new StompDestination(); - $destination->setType(StompDestination::TYPE_EXCHANGE); + $destination->setType($this->useExchangePrefix ? StompDestination::TYPE_EXCHANGE : StompDestination::TYPE_TOPIC); $destination->setStompName($name); return $destination; diff --git a/pkg/stomp/Tests/StompConnectionFactoryConfigTest.php b/pkg/stomp/Tests/StompConnectionFactoryConfigTest.php index e8705a010..af8e71bd7 100644 --- a/pkg/stomp/Tests/StompConnectionFactoryConfigTest.php +++ b/pkg/stomp/Tests/StompConnectionFactoryConfigTest.php @@ -55,6 +55,7 @@ public static function provideConfigs() yield [ null, [ + 'target' => 'rabbitmq', 'host' => 'localhost', 'port' => 61613, 'login' => 'guest', @@ -71,6 +72,7 @@ public static function provideConfigs() yield [ 'stomp:', [ + 'target' => 'rabbitmq', 'host' => 'localhost', 'port' => 61613, 'login' => 'guest', @@ -87,6 +89,7 @@ public static function provideConfigs() yield [ [], [ + 'target' => 'rabbitmq', 'host' => 'localhost', 'port' => 61613, 'login' => 'guest', @@ -103,6 +106,43 @@ public static function provideConfigs() yield [ 'stomp://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, + ], + ]; + + 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, + ], + ]; + + yield [ + 'stomp+rabbitmq://localhost:1234?foo=bar&lazy=0&sync=true', + [ + 'target' => 'rabbitmq', 'host' => 'localhost', 'port' => 1234, 'login' => 'guest', @@ -120,6 +160,7 @@ public static function provideConfigs() yield [ ['dsn' => 'stomp://localhost:1234/theVhost?foo=bar&lazy=0&sync=true', 'baz' => 'bazVal', 'foo' => 'fooVal'], [ + 'target' => 'rabbitmq', 'host' => 'localhost', 'port' => 1234, 'login' => 'guest', @@ -138,6 +179,7 @@ public static function provideConfigs() yield [ ['dsn' => 'stomp:///%2f'], [ + 'target' => 'rabbitmq', 'host' => 'localhost', 'port' => 61613, 'login' => 'guest', @@ -154,6 +196,7 @@ public static function provideConfigs() yield [ ['host' => 'localhost', 'port' => 1234, 'foo' => 'bar'], [ + 'target' => 'rabbitmq', 'host' => 'localhost', 'port' => 1234, 'login' => 'guest', diff --git a/pkg/stomp/Tests/StompConnectionFactoryTest.php b/pkg/stomp/Tests/StompConnectionFactoryTest.php index 18a13463f..91986e6d0 100644 --- a/pkg/stomp/Tests/StompConnectionFactoryTest.php +++ b/pkg/stomp/Tests/StompConnectionFactoryTest.php @@ -25,6 +25,31 @@ public function testShouldCreateLazyContext() $this->assertInstanceOf(StompContext::class, $context); $this->assertAttributeEquals(null, 'stomp', $context); + $this->assertAttributeEquals(true, 'useExchangePrefix', $context); $this->assertInternalType('callable', $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/StompContextTest.php b/pkg/stomp/Tests/StompContextTest.php index 49297d3e1..69b577e85 100644 --- a/pkg/stomp/Tests/StompContextTest.php +++ b/pkg/stomp/Tests/StompContextTest.php @@ -79,7 +79,7 @@ public function testCreateQueueShouldCreateDestinationIfNameIsFullDestinationStr $this->assertEquals('/amq/queue/name/routing-key', $destination->getQueueName()); } - public function testShouldCreateTopicInstance() + public function testShouldCreateTopicInstanceWithExchangePrefix() { $context = new StompContext($this->createStompClientMock()); @@ -91,6 +91,18 @@ public function testShouldCreateTopicInstance() $this->assertSame(StompDestination::TYPE_EXCHANGE, $topic->getType()); } + public function testShouldCreateTopicInstanceWithTopicPrefix() + { + $context = new StompContext($this->createStompClientMock(), false); + + $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());