From 52d361442e039826cb0b30d5c5dd4659f7a63b62 Mon Sep 17 00:00:00 2001 From: Manuel Reinhard Date: Tue, 12 Oct 2021 14:46:04 +0200 Subject: [PATCH 01/16] Replace doctrine/common with doctrine/cache --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 30fe920..85fdc35 100755 --- a/composer.json +++ b/composer.json @@ -18,7 +18,7 @@ }, "require": { "php": ">=5.6.0", - "doctrine/common": "~2.4", + "doctrine/cache": "~1.11", "symfony/dependency-injection": "~2.3|^3.0|^4.0", "symfony/config": "~2.3|^3.0|^4.0", "symfony/http-kernel": "~2.3|^3.0|^4.0", From 13a7a4c74c9a82ee8311dd16c3036b448373fc0f Mon Sep 17 00:00:00 2001 From: Manuel Reinhard Date: Tue, 12 Oct 2021 14:46:22 +0200 Subject: [PATCH 02/16] Adapt unit tests to new PhpUnit version --- .gitignore | 1 + integration_tests/Provider/IronMqProviderTest.php | 7 ++++--- tests/DependencyInjection/UecodeQPushExtensionTest.php | 5 +++-- tests/Event/EventsTest.php | 3 ++- tests/Event/MessageEventTest.php | 7 ++++--- tests/Event/NotificationEventTest.php | 7 ++++--- tests/EventListener/RequestListenerTest.php | 5 +++-- tests/Message/BaseMessageTest.php | 3 ++- tests/Message/MessageTest.php | 4 ++-- tests/Message/NotificationTest.php | 4 ++-- tests/Provider/AbstractProviderTest.php | 7 ++++--- tests/Provider/AwsProviderTest.php | 7 ++++--- tests/Provider/CustomProviderTest.php | 5 +++-- tests/Provider/FileProviderTest.php | 7 ++++--- tests/Provider/IronMqProviderTest.php | 7 ++++--- tests/Provider/ProviderRegisteryTest.php | 3 ++- tests/Provider/SyncProviderTest.php | 5 +++-- 17 files changed, 51 insertions(+), 36 deletions(-) diff --git a/.gitignore b/.gitignore index e673d7b..a82115d 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ /coverage .idea /nbproject +/.phpunit.result.cache diff --git a/integration_tests/Provider/IronMqProviderTest.php b/integration_tests/Provider/IronMqProviderTest.php index 33e128e..6f8359c 100755 --- a/integration_tests/Provider/IronMqProviderTest.php +++ b/integration_tests/Provider/IronMqProviderTest.php @@ -3,12 +3,13 @@ namespace Uecode\Bundle\QPushBundle\IntegrationTests\Provider; use IronMQ\IronMQ; +use PHPUnit\Framework\TestCase; use Uecode\Bundle\QPushBundle\Event\MessageEvent; use Uecode\Bundle\QPushBundle\Event\NotificationEvent; use Uecode\Bundle\QPushBundle\Message\Notification; use Uecode\Bundle\QPushBundle\Provider\IronMqProvider; -class IronMqProviderTest extends \PHPUnit_Framework_TestCase +class IronMqProviderTest extends TestCase { /** * Mock Client @@ -23,7 +24,7 @@ class IronMqProviderTest extends \PHPUnit_Framework_TestCase */ private $client; - public function setUp() + public function setUp(): void { if (!defined("IRONMQ_TOKEN") || IRONMQ_TOKEN == 'CHANGE_ME') { throw new \RuntimeException('"IRONMQ_TOKEN" must be defined in tests/bootstrap.php'); @@ -43,7 +44,7 @@ public function setUp() $this->provider = $this->getIronMqProvider(); } - public function tearDown() + public function tearDown(): void { if (!is_null($this->provider)) { $this->provider->destroy(); diff --git a/tests/DependencyInjection/UecodeQPushExtensionTest.php b/tests/DependencyInjection/UecodeQPushExtensionTest.php index 2523232..5d4ac00 100644 --- a/tests/DependencyInjection/UecodeQPushExtensionTest.php +++ b/tests/DependencyInjection/UecodeQPushExtensionTest.php @@ -22,6 +22,7 @@ namespace Uecode\Bundle\QPushBundle\Tests\DependencyInjection; +use PHPUnit\Framework\TestCase; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; @@ -31,7 +32,7 @@ /** * @author Keith Kirk */ -class UecodeQPushExtensionTest extends \PHPUnit_Framework_TestCase +class UecodeQPushExtensionTest extends TestCase { /** * QPush Extension @@ -47,7 +48,7 @@ class UecodeQPushExtensionTest extends \PHPUnit_Framework_TestCase */ private $container; - public function setUp() + public function setUp(): void { $this->extension = new UecodeQPushExtension(); $this->container = new ContainerBuilder(new ParameterBag(['kernel.cache_dir' => '/tmp'])); diff --git a/tests/Event/EventsTest.php b/tests/Event/EventsTest.php index 0250dac..088e10f 100644 --- a/tests/Event/EventsTest.php +++ b/tests/Event/EventsTest.php @@ -22,12 +22,13 @@ namespace Uecode\Bundle\QPushBundle\Tests\Event; +use PHPUnit\Framework\TestCase; use Uecode\Bundle\QPushBundle\Event\Events; /** * @author Keith Kirk */ -class EventsTest extends \PHPUnit_Framework_TestCase +class EventsTest extends TestCase { public function testConstants() { diff --git a/tests/Event/MessageEventTest.php b/tests/Event/MessageEventTest.php index 616df7f..3859e22 100644 --- a/tests/Event/MessageEventTest.php +++ b/tests/Event/MessageEventTest.php @@ -22,6 +22,7 @@ namespace Uecode\Bundle\QPushBundle\Tests\Event; +use PHPUnit\Framework\TestCase; use Uecode\Bundle\QPushBundle\Event\MessageEvent; use Uecode\Bundle\QPushBundle\Message\Message; @@ -29,16 +30,16 @@ /** * @author Keith Kirk */ -class MessageEventTest extends \PHPUnit_Framework_TestCase +class MessageEventTest extends TestCase { protected $event; - public function setUp() + public function setUp(): void { $this->event = new MessageEvent('test', new Message(123, ['foo' => 'bar'], ['bar' => 'baz'])); } - public function tearDown() + public function tearDown(): void { $this->event = null; } diff --git a/tests/Event/NotificationEventTest.php b/tests/Event/NotificationEventTest.php index 46063cf..320a017 100644 --- a/tests/Event/NotificationEventTest.php +++ b/tests/Event/NotificationEventTest.php @@ -22,6 +22,7 @@ namespace Uecode\Bundle\QPushBundle\Tests\Event; +use PHPUnit\Framework\TestCase; use Uecode\Bundle\QPushBundle\Event\NotificationEvent; use Uecode\Bundle\QPushBundle\Message\Notification; @@ -29,11 +30,11 @@ /** * @author Keith Kirk */ -class NotificationEventTest extends \PHPUnit_Framework_TestCase +class NotificationEventTest extends TestCase { protected $event; - public function setUp() + public function setUp(): void { $this->event = new NotificationEvent( 'test', @@ -42,7 +43,7 @@ public function setUp() ); } - public function tearDown() + public function tearDown(): void { $this->event = null; } diff --git a/tests/EventListener/RequestListenerTest.php b/tests/EventListener/RequestListenerTest.php index a47bd1a..5641890 100644 --- a/tests/EventListener/RequestListenerTest.php +++ b/tests/EventListener/RequestListenerTest.php @@ -22,6 +22,7 @@ namespace Uecode\Bundle\QPushBundle\Tests\EventListener; +use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -35,7 +36,7 @@ /** * @author Keith Kirk */ -class RequestListenerTest extends \PHPUnit_Framework_TestCase +class RequestListenerTest extends TestCase { /** * @var EventDispatcher @@ -47,7 +48,7 @@ class RequestListenerTest extends \PHPUnit_Framework_TestCase */ protected $event; - public function setUp() + public function setUp(): void { $this->dispatcher = new EventDispatcher('UTF-8'); $listener = new RequestListener($this->dispatcher); diff --git a/tests/Message/BaseMessageTest.php b/tests/Message/BaseMessageTest.php index a0dbd46..8e77ca2 100644 --- a/tests/Message/BaseMessageTest.php +++ b/tests/Message/BaseMessageTest.php @@ -22,12 +22,13 @@ namespace Uecode\Bundle\QpushBundle\Tests\Message; +use PHPUnit\Framework\TestCase; use Uecode\Bundle\QPushBundle\Message; /** * @author Keith Kirk */ -abstract class BaseMessageTest extends \PHPUnit_Framework_TestCase +abstract class BaseMessageTest extends TestCase { protected $message; diff --git a/tests/Message/MessageTest.php b/tests/Message/MessageTest.php index 4b34e42..e4e345e 100644 --- a/tests/Message/MessageTest.php +++ b/tests/Message/MessageTest.php @@ -29,12 +29,12 @@ */ class MessageTest extends BaseMessageTest { - public function setUp() + public function setUp(): void { $this->message = new Message(123, ['foo' => 'bar'], ['baz' => 'qux']); } - public function tearDown() + public function tearDown(): void { $this->message = null; } diff --git a/tests/Message/NotificationTest.php b/tests/Message/NotificationTest.php index 641ce3c..80432f0 100644 --- a/tests/Message/NotificationTest.php +++ b/tests/Message/NotificationTest.php @@ -29,12 +29,12 @@ */ class NotificationTest extends BaseMessageTest { - public function setUp() + public function setUp(): void { $this->message = new Notification(123, ['foo' => 'bar'], ['baz' => 'qux']); } - public function tearDown() + public function tearDown(): void { $this->message = null; } diff --git a/tests/Provider/AbstractProviderTest.php b/tests/Provider/AbstractProviderTest.php index a00a708..376b898 100644 --- a/tests/Provider/AbstractProviderTest.php +++ b/tests/Provider/AbstractProviderTest.php @@ -22,6 +22,7 @@ namespace Uecode\Bundle\QPushBundle\Tests\Provider; +use PHPUnit\Framework\TestCase; use Uecode\Bundle\QPushBundle\Provider\ProviderInterface; use Uecode\Bundle\QPushBundle\Event\MessageEvent; @@ -33,16 +34,16 @@ /** * @author Keith Kirk */ -class AbstractProviderTest extends \PHPUnit_Framework_TestCase +class AbstractProviderTest extends TestCase { protected $provider; - public function setUp() + public function setUp(): void { $this->provider = $this->getTestProvider(); } - public function tearDown() + public function tearDown(): void { $this->provider = null; diff --git a/tests/Provider/AwsProviderTest.php b/tests/Provider/AwsProviderTest.php index fc01198..b8f8762 100755 --- a/tests/Provider/AwsProviderTest.php +++ b/tests/Provider/AwsProviderTest.php @@ -22,6 +22,7 @@ namespace Uecode\Bundle\QPushBundle\Tests\Provider; +use PHPUnit\Framework\TestCase; use Uecode\Bundle\QPushBundle\Provider\AwsProvider; use Uecode\Bundle\QPushBundle\Event\MessageEvent; @@ -35,7 +36,7 @@ /** * @author Keith Kirk */ -class AwsProviderTest extends \PHPUnit_Framework_TestCase +class AwsProviderTest extends TestCase { /** * Mock Client @@ -44,12 +45,12 @@ class AwsProviderTest extends \PHPUnit_Framework_TestCase */ protected $provider; - public function setUp() + public function setUp(): void { $this->provider = $this->getAwsProvider(); } - public function tearDown() + public function tearDown(): void { $this->provider = null; } diff --git a/tests/Provider/CustomProviderTest.php b/tests/Provider/CustomProviderTest.php index 7e482ba..93207b5 100644 --- a/tests/Provider/CustomProviderTest.php +++ b/tests/Provider/CustomProviderTest.php @@ -3,10 +3,11 @@ namespace Uecode\Bundle\QPushBundle\Tests\Provider; +use PHPUnit\Framework\TestCase; use Uecode\Bundle\QPushBundle\Provider\CustomProvider; use Uecode\Bundle\QPushBundle\Tests\MockClient\CustomMockClient; -class CustomProviderTest extends \PHPUnit_Framework_TestCase +class CustomProviderTest extends TestCase { /** * @var \Uecode\Bundle\QPushBundle\Provider\SyncProvider @@ -20,7 +21,7 @@ class CustomProviderTest extends \PHPUnit_Framework_TestCase private $mock; - public function setUp() + public function setUp(): void { $this->provider = $this->getCustomProvider(); } diff --git a/tests/Provider/FileProviderTest.php b/tests/Provider/FileProviderTest.php index d6dbeb0..e890744 100644 --- a/tests/Provider/FileProviderTest.php +++ b/tests/Provider/FileProviderTest.php @@ -2,6 +2,7 @@ namespace Uecode\Bundle\QPushBundle\Tests\Provider; +use PHPUnit\Framework\TestCase; use Symfony\Component\Finder\Finder; use Uecode\Bundle\QPushBundle\Event\MessageEvent; use Uecode\Bundle\QPushBundle\Provider\FileProvider; @@ -9,7 +10,7 @@ /** * @author James Moey */ -class FileProviderTest extends \PHPUnit_Framework_TestCase +class FileProviderTest extends TestCase { /** @var FileProvider */ protected $provider; @@ -17,7 +18,7 @@ class FileProviderTest extends \PHPUnit_Framework_TestCase protected $queueHash; protected $umask; - public function setUp() + public function setUp(): void { $this->umask = umask(0); $this->basePath = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.time().rand(0, 1000); @@ -25,7 +26,7 @@ public function setUp() $this->provider = $this->getFileProvider(); } - public function tearDown() + public function tearDown(): void { $this->clean($this->basePath); umask($this->umask); diff --git a/tests/Provider/IronMqProviderTest.php b/tests/Provider/IronMqProviderTest.php index 39df439..b682ca5 100755 --- a/tests/Provider/IronMqProviderTest.php +++ b/tests/Provider/IronMqProviderTest.php @@ -22,6 +22,7 @@ namespace Uecode\Bundle\QPushBundle\Tests\Provider; +use PHPUnit\Framework\TestCase; use Uecode\Bundle\QPushBundle\Provider\IronMqProvider; use Uecode\Bundle\QPushBundle\Event\MessageEvent; @@ -35,7 +36,7 @@ /** * @author Keith Kirk */ -class IronMqProviderTest extends \PHPUnit_Framework_TestCase +class IronMqProviderTest extends TestCase { /** * Mock Client @@ -44,12 +45,12 @@ class IronMqProviderTest extends \PHPUnit_Framework_TestCase */ protected $provider; - public function setUp() + public function setUp(): void { $this->provider = $this->getIronMqProvider(); } - public function tearDown() + public function tearDown(): void { $this->provider = null; } diff --git a/tests/Provider/ProviderRegisteryTest.php b/tests/Provider/ProviderRegisteryTest.php index 37bc9e0..487d985 100644 --- a/tests/Provider/ProviderRegisteryTest.php +++ b/tests/Provider/ProviderRegisteryTest.php @@ -22,12 +22,13 @@ namespace Uecode\Bundle\QPushBundle\Tests\Provider; +use PHPUnit\Framework\TestCase; use Uecode\Bundle\QPushBundle\Provider\ProviderRegistry; /** * @author Keith Kirk */ -class ProviderRegistryTest extends \PHPUnit_Framework_TestCase +class ProviderRegistryTest extends TestCase { public function testRegistry() { diff --git a/tests/Provider/SyncProviderTest.php b/tests/Provider/SyncProviderTest.php index 94eb383..ca3c626 100644 --- a/tests/Provider/SyncProviderTest.php +++ b/tests/Provider/SyncProviderTest.php @@ -3,10 +3,11 @@ namespace Uecode\Bundle\QPushBundle\Tests\Provider; +use PHPUnit\Framework\TestCase; use Uecode\Bundle\QPushBundle\Event\Events; use Uecode\Bundle\QPushBundle\Provider\SyncProvider; -class SyncProviderTest extends \PHPUnit_Framework_TestCase +class SyncProviderTest extends TestCase { /** * @var \Uecode\Bundle\QPushBundle\Provider\SyncProvider @@ -23,7 +24,7 @@ class SyncProviderTest extends \PHPUnit_Framework_TestCase */ protected $logger; - public function setUp() + public function setUp(): void { $this->dispatcher = $this->createMock( 'Symfony\Component\EventDispatcher\EventDispatcherInterface' From ce09e3675856aebdf4836402d819339ed32adeab Mon Sep 17 00:00:00 2001 From: Manuel Reinhard Date: Tue, 12 Oct 2021 15:39:59 +0200 Subject: [PATCH 03/16] Simplified version to support AWS only --- .travis.yml | 40 -- README.md | 14 +- composer.json | 45 +- docs/Makefile | 153 ------- docs/aws-provider.rst | 120 ------ docs/conf.py | 242 ----------- docs/configuration.rst | 168 -------- docs/console-commands.rst | 43 -- docs/custom-provider.rst | 23 - docs/file-provider.rst | 23 - docs/index.rst | 24 -- docs/installation.rst | 25 -- docs/iron-mq-provider.rst | 130 ------ docs/sync-provider.rst | 24 -- docs/usage.rst | 182 -------- .../Provider/IronMqProviderTest.php | 205 --------- phpunit.xml.dist | 5 - src/Command/QueueDestroyCommand.php | 2 +- src/Command/QueueReceiveCommand.php | 2 +- src/DependencyInjection/Configuration.php | 23 +- .../UecodeQPushExtension.php | 48 +-- src/Entity/DoctrineMessage.php | 236 ---------- src/EventListener/RequestListener.php | 12 +- src/Provider/AbstractProvider.php | 47 -- src/Provider/AwsProvider.php | 173 ++------ src/Provider/CustomProvider.php | 125 ------ src/Provider/DoctrineProvider.php | 301 ------------- src/Provider/FileProvider.php | 168 -------- src/Provider/IronMqProvider.php | 406 ------------------ src/Provider/ProviderInterface.php | 37 +- src/Provider/SyncProvider.php | 78 ---- src/Resources/config/config.yml | 4 +- src/Resources/config/parameters.yml | 5 - src/Resources/config/services.yml | 6 - .../UecodeQPushExtensionTest.php | 8 - tests/Event/NotificationEventTest.php | 4 +- tests/EventListener/RequestListenerTest.php | 52 +-- tests/Fixtures/config_test.yml | 51 +-- tests/MockClient/CustomMockClient.php | 72 ---- tests/MockClient/IronMqMockClient.php | 111 ----- tests/Provider/AbstractProviderTest.php | 36 +- tests/Provider/AwsProviderTest.php | 63 +-- tests/Provider/CustomProviderTest.php | 107 ----- tests/Provider/FileProviderTest.php | 214 --------- tests/Provider/IronMqProviderTest.php | 207 --------- tests/Provider/ProviderRegisteryTest.php | 2 +- tests/Provider/SyncProviderTest.php | 124 ------ tests/Provider/TestProvider.php | 4 +- 48 files changed, 110 insertions(+), 4084 deletions(-) delete mode 100644 .travis.yml delete mode 100644 docs/Makefile delete mode 100644 docs/aws-provider.rst delete mode 100644 docs/conf.py delete mode 100644 docs/configuration.rst delete mode 100644 docs/console-commands.rst delete mode 100644 docs/custom-provider.rst delete mode 100644 docs/file-provider.rst delete mode 100644 docs/index.rst delete mode 100644 docs/installation.rst delete mode 100644 docs/iron-mq-provider.rst delete mode 100644 docs/sync-provider.rst delete mode 100644 docs/usage.rst delete mode 100755 integration_tests/Provider/IronMqProviderTest.php delete mode 100644 src/Entity/DoctrineMessage.php delete mode 100755 src/Provider/CustomProvider.php delete mode 100644 src/Provider/DoctrineProvider.php delete mode 100644 src/Provider/FileProvider.php delete mode 100755 src/Provider/IronMqProvider.php delete mode 100644 src/Provider/SyncProvider.php delete mode 100644 tests/MockClient/CustomMockClient.php delete mode 100644 tests/MockClient/IronMqMockClient.php delete mode 100644 tests/Provider/CustomProviderTest.php delete mode 100644 tests/Provider/FileProviderTest.php delete mode 100755 tests/Provider/IronMqProviderTest.php delete mode 100644 tests/Provider/SyncProviderTest.php diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 328f165..0000000 --- a/.travis.yml +++ /dev/null @@ -1,40 +0,0 @@ -language: php - -sudo: false - -cache: - directories: - - $HOME/.composer/cache/files - -php: - - hhvm - -matrix: - fast_finish: true - include: - - php: 5.6 - env: SYMFONY_VERSION=2.7.* - - php: 5.6 - env: SYMFONY_VERSION=2.8.* - - php: 5.6 - env: SYMFONY_VERSION=3.4.* - - php: 7.0 - env: COVERAGE=yes - allow_failures: - - php: hhvm - -before_install: - - if [ "$COVERAGE" != "yes" -a "$TRAVIS_PHP_VERSION" != "hhvm" ]; then phpenv config-rm xdebug.ini; fi - - composer self-update - - if [ "$SYOMFONY_VERSION" != "" ]; then composer require symfony/framework-bundle:${SYMFONY_VERSION} --no-update; fi - -install: - - composer install --prefer-dist - -script: - - if [ "$COVERAGE" = "yes" ]; then ./vendor/bin/simple-phpunit --coverage-text --coverage-clover=coverage.clover --testsuite "UecodeQPushBundle Test Suite"; else ./vendor/bin/simple-phpunit --testsuite "UecodeQPushBundle Test Suite"; fi - -after_script: - - if [ "$COVERAGE" = "yes" ]; then wget https://scrutinizer-ci.com/ocular.phar; fi - - if [ "$COVERAGE" = "yes" ]; then php ocular.phar code-coverage:upload --format=php-clover coverage.clover; fi - diff --git a/README.md b/README.md index 8389f01..783ba4c 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,11 @@ QPush - Symfony2 Push Queue Bundle ================================== -[![Build Status](https://img.shields.io/travis/uecode/qpush-bundle/master.svg?style=flat-square)](https://travis-ci.org/uecode/qpush-bundle) -[![Quality Score](https://img.shields.io/scrutinizer/g/uecode/qpush-bundle.svg?style=flat-square)](https://scrutinizer-ci.com/g/uecode/qpush-bundle/) -[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/uecode/qpush-bundle.svg?style=flat-square)](https://scrutinizer-ci.com/g/uecode/qpush-bundle/) -[![Total Downloads](http://img.shields.io/packagist/dt/uecode/qpush-bundle.svg?style=flat-square)](https://packagist.org/packages/uecode/qpush-bundle) +---- + +This is a simplified fork, only providing AWS implementation. No public support or maintenance is provided here. + +---- ## Overview This bundle allows you to easily consume messages from Push Queues by simply @@ -51,16 +52,13 @@ and provider options in the [full documentation](http://qpush-bundle.rtfd.org). uecode_qpush: providers: - ironmq: - token: YOUR_IRON_MQ_TOKEN_HERE - project_id: YOUR_IRON_MQ_PROJECT_ID_HERE aws: key: YOUR_AWS_KEY_HERE secret: YOUR_AWS_SECRET_HERE region: YOUR_AWS_REGION_HERE queues: my_queue_key: - provider: ironmq #or aws + provider: aws options: queue_name: my_queue_name #optional. the queue name used on the provider push_notifications: true diff --git a/composer.json b/composer.json index 85fdc35..23c94c8 100755 --- a/composer.json +++ b/composer.json @@ -2,46 +2,21 @@ "name": "uecode/qpush-bundle", "type": "library", "description": "Asynchronous processing for Symfony using Push Queues", - "keywords": ["qpush", "pub-sub", "aws", "iron mq", "asynch", "push", "symfony", "bundle" ], - "homepage": "https://github.com/uecode/qpush-bundle", + "keywords": ["qpush", "aws", "push", "symfony", "bundle" ], + "homepage": "https://github.com/ticketpark/qpush-bundle", "license": "Apache-2.0", - "authors": [ - { - "name": "Keith Kirk", - "email": "kkirk@undergroundelephant.com", - "role": "developer", - "homepage": "http://undergroundelephant.com" - } - ], - "support": { - "email": "kkirk@undergroundelephant.com" - }, "require": { - "php": ">=5.6.0", - "doctrine/cache": "~1.11", - "symfony/dependency-injection": "~2.3|^3.0|^4.0", - "symfony/config": "~2.3|^3.0|^4.0", - "symfony/http-kernel": "~2.3|^3.0|^4.0", - "symfony/console": "~2.3|^3.0|^4.0", - "symfony/monolog-bundle": "~2.3|^3.0|^4.0" + "php": ">=7.3", + "symfony/dependency-injection": "^4.0", + "symfony/config": "^4.0", + "symfony/http-kernel": "^4.0", + "symfony/console": "^4.0", + "aws/aws-sdk-php": "~2.5", + "doctrine/collections": "^1.6" }, "require-dev": { - "aws/aws-sdk-php": "~2.5", - "iron-io/iron_mq": "^4.0", - "symfony/finder": "~2.3|^3.0|^4.0", - "symfony/filesystem": "~2.3|^3.0|^4.0", "symfony/phpunit-bridge": "^4.0", - "symfony/yaml": "~2.8|^3.0|^4.0", - "doctrine/orm": "^2.4.8", - "stof/doctrine-extensions-bundle": "^1.2" - }, - "suggest": { - "aws/aws-sdk-php": "Required to use AWS as a Queue Provider", - "iron-io/iron_mq": "Required to use IronMQ as a Queue Provider", - "symfony/finder": "Required to use File as a Queue Provider", - "symfony/filesystem": "Required to use File as a Queue Provider", - "doctrine/orm": "Required to use Doctrine as a Queue Provider", - "stof/doctrine-extensions-bundle": "Required to use Doctrine as a Queue Provider" + "symfony/yaml": "^4.0" }, "autoload": { "psr-4": { diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index 307e6e6..0000000 --- a/docs/Makefile +++ /dev/null @@ -1,153 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - -rm -rf $(BUILDDIR)/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/QPushBundle.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/QPushBundle.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/QPushBundle" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/QPushBundle" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/aws-provider.rst b/docs/aws-provider.rst deleted file mode 100644 index 8546a0b..0000000 --- a/docs/aws-provider.rst +++ /dev/null @@ -1,120 +0,0 @@ -AWS Provider ------------- - -The AWS Provider uses SQS & SNS to create a Push Queue model. SNS is optional with -this provider and its possible to use just SQS by utilizing the provided Console -Command (``uecode:qpush:receive``) to poll the queue. - -Configuration -^^^^^^^^^^^^^ - -This provider relies on the `AWS SDK PHP `_ library, which -needs to be required in your ``composer.json`` file. - -This bundle will support both v2 and v3 of the AWS SDK. - -.. code-block:: js - - { - require: { - "aws/aws-sdk-php": : "2.*" #OR "3.*" - } - } - -From there, the rest of the configuration is simple. You need to provide your -credentials in your configuration. - -.. code-block:: yaml - - #app/config.yml - - uecode_qpush: - providers: - my_provider: - driver: aws - key: - secret: - region: us-east-1 - queues: - my_queue_name: - provider: my_provider - options: - push_notifications: true - subscribers: - - { endpoint: http://example.com/qpush, protocol: http } - -You may exclude the aws key and secret if you are using IAM role in EC2. - -Using SNS -^^^^^^^^^ - -If you set ``push_notifications`` to ``true`` in your queue config, this provider -will automatically create the SNS Topic, subscribe your SQS queue to it, as well -as loop over your list of ``subscribers``, adding them to your Topic. - -This provider automatically handles Subscription Confirmations sent from SNS, as -long as the HTTP endpoint you've listed is externally accessible and has the QPush Bundle -properly installed and configured. - -Overriding Queue Options -^^^^^^^^^^^^^^^^^^^^^^^^ - -It's possible to override the default queue options that are set in your config file -when sending or receiving messages. - -**Publishing** - -The ``publish()`` method takes an array as a second argument. For the AWS Provider -you are able to change the options listed below per publish. - -If you disable ``push_notifications`` for a message, it will skip using SNS and -only write the message to SQS. You will need to manually poll the SQS queue to -fetch those messages. - -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ -| Option | Description | Default Value | -+==========================+===========================================================================================+===============+ -| ``push_notifications`` | Whether or not to POST notifications to subscribers of a Queue | ``false`` | -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ -| ``message_delay`` | Time in seconds before a published Message is available to be read in a Queue | ``0`` | -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ - -.. code-block:: php - - $message = ['foo' => 'bar']; - - // Optional config to override default options - $options = [ - 'push_notifications' => 0, - 'message_delay' => 1 - ]; - - $this->get('uecode_qpush.my_queue_name')->publish($message, $options); - - -**Receiving** - -The ``receive()`` method takes an array as a second argument. For the AWS Provider -you are able to change the options listed below per attempt to receive messages. - -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ -| Option | Description | Default Value | -+==========================+===========================================================================================+===============+ -| ``messages_to_receive`` | Maximum amount of messages that can be received when polling the queue | ``1`` | -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ -| ``receive_wait_time`` | If supported, time in seconds to leave the polling request open - for long polling | ``3`` | -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ - -.. code-block:: php - - // Optional config to override default options - $options = [ - 'messages_to_receive' => 3, - 'receive_wait_time' => 10 - ]; - - $messages = $this->get('uecode_qpush.my_queue_name')->receive($options); - - foreach ($messages as $message) { - echo $message->getBody(); - } diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index 68d3758..0000000 --- a/docs/conf.py +++ /dev/null @@ -1,242 +0,0 @@ -# -*- coding: utf-8 -*- -# -# QPush Bundle documentation build configuration file, created by -# sphinx-quickstart on Sat Feb 22 19:40:44 2014. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys, os - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) - -# -- General configuration ----------------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = [] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'QPush Bundle' -copyright = u'2014, Keith Kirk' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '1.1.3' -# The full version, including alpha/beta/rc tags. -release = '1.1.3' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'default' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'QPushBundledoc' - - -# -- Options for LaTeX output -------------------------------------------------- - -latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('index', 'QPushBundle.tex', u'QPush Bundle Documentation', - u'Keith Kirk', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output -------------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'qpushbundle', u'QPush Bundle Documentation', - [u'Keith Kirk'], 1) -] - -# If true, show URL addresses after external links. -#man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------------ - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ('index', 'QPushBundle', u'QPush Bundle Documentation', - u'Keith Kirk', 'QPushBundle', 'One line description of project.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -#texinfo_appendices = [] - -# If false, no module index is generated. -#texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' diff --git a/docs/configuration.rst b/docs/configuration.rst deleted file mode 100644 index eaa137b..0000000 --- a/docs/configuration.rst +++ /dev/null @@ -1,168 +0,0 @@ -Configure the Bundle -==================== - -The bundle allows you to specify different Message Queue providers - however, -Amazon AWS and IronMQ are the only ones currently supported. Blocking, synchronous queues -are also supported through the ``sync`` driver to aid development and debugging. - -We are actively looking to add more and would be more than happy to accept contributions. - -Providers ---------- - -This bundle allows you to configure and use multiple supported providers with in the same -application. Each queue that you create is attached to one of your registered providers -and can have its own configuration options. - -Providers may have their own dependencies that should be added to your ``composer.json`` file. - -For specific instructions on how to configure each provider, please view their documents. - -.. toctree:: - :maxdepth: 2 - - aws-provider - iron-mq-provider - sync-provider - file-provider - custom-provider - -Caching -------- - -Providers can leverage a caching layer to limit the amount of calls to the Message Queue -for basic lookup functionality - this is important for things like AWS's ARN values, etc. - -By default the library will attempt to use file cache, however you can pass your -own cache service, as long as its an instance of ``Doctrine\Common\Cache\Cache``. - -The configuration parameter ``cache_service`` expects the container service id of a registered -Cache service. See below. - -.. code-block:: yaml - - #app/config.yml - - services: - my_cache_service: - class: My\Caching\CacheService - - uecode_qpush: - cache_service: my_cache_service - -**Note:** *Though the Queue Providers will attempt to create queues if they do not exist when publishing or receiving messages, -it is highly recommended that you run the included console command to build queues and warm cache from the CLI beforehand.* - -Queue Options -------------- - -Each queue can have their own options that determine how messages are published or received. -The options and their descriptions are listed below. - -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ -| Option | Description | Default Value | -+=================================+============================================================================================+===============+ -| ``queue_name`` | The name used to describe the queue on the Provider's side | ``null`` | -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ -| ``push_notifications`` | Whether or not to POST notifications to subscribers of a Queue | ``false`` | -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ -| ``notification_retries`` | How many attempts notifications are resent in case of errors - if supported | ``3`` | -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ -| ``message_delay`` | Time in seconds before a published Message is available to be read in a Queue | ``0`` | -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ -| ``message_timeout`` | Time in seconds a worker has to delete a Message before it is available to other workers | ``30`` | -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ -| ``message_expiration`` | Time in seconds that Messages may remain in the Queue before being removed | ``604800`` | -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ -| ``messages_to_receive`` | Maximum amount of messages that can be received when polling the queue | ``1`` | -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ -| ``receive_wait_time`` | If supported, time in seconds to leave the polling request open - for long polling | ``3`` | -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ -| ``fifo`` | If supported (only aws), sets queue into FIFO mode | ``false`` | -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ -| ``content_based_deduplication`` | If supported (only aws), turns on automatic deduplication id based on the message content | ``false`` | -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ -| ``subscribers`` | An array of Subscribers, containing an ``endpoint`` and ``protocol`` | ``empty`` | -+---------------------------------+--------------------------------------------------------------------------------------------+---------------+ - -Symfony Application as a Subscriber ------------------------------------ - -The QPush Bundle uses a Request Listener which will capture and dispatch notifications from your queue providers for you. The specific route you use does not matter. - -In most cases, it is recommended to just list the host or domain for your Symfony application as the ``endpoint`` of your subscriber. You do not need to create a new action for QPush to receive messages. - -Logging with Monolog --------------------- - -By default, logging is enabled in the Qpush Bundle and uses Monolog, configured -via the MonologBundle. You can toggle the logging behavior by setting -``logging_enabled`` to ``false``. - -Logs will output to your default Symfony environment logs using the 'qpush' channel. - -Example Configuration ---------------------- - -A working configuration would look like the following - -.. code-block:: yaml - - uecode_qpush: - cache_service: null - logging_enabled: true - providers: - aws: - driver: aws #optional for providers named 'aws' or 'ironmq' - key: YOUR_AWS_KEY_HERE - secret: YOUR_AWS_SECRET_HERE - region: YOUR_AWS_REGION_HERE - another_aws_provider: - driver: aws #required for named providers - key: YOUR_AWS_KEY_HERE - secret: YOUR_AWS_SECRET_HERE - region: YOUR_AWS_REGION_HERE - ironmq: - driver: aws #optional for providers named 'aws' or 'ironmq' - token: YOUR_IRONMQ_TOKEN_HERE - project_id: YOUR_IRONMQ_PROJECT_ID_HERE - in_band: - driver: sync - custom_provider: - driver: custom - service: YOUR_CUSTOM_SERVICE_ID - queues: - my_queue_key: - provider: ironmq #or aws or in_band or another_aws_provider - options: - queue_name: my_actual_queue_name - push_notifications: true - notification_retries: 3 - message_delay: 0 - message_timeout: 30 - message_expiration: 604800 - messages_to_receive: 1 - receive_wait_time: 3 - fifo: false - content_based_deduplication: false - subscribers: - - { endpoint: http://example1.com/, protocol: http } - - { endpoint: http://example2.com/, protocol: http } - my_fifo_queue_key: - provider: aws - options: - queue_name: my_actual_queue_name.fifo - push_notifications: false - notification_retries: 3 - message_delay: 0 - message_timeout: 30 - message_expiration: 604800 - messages_to_receive: 1 - receive_wait_time: 3 - fifo: true - content_based_deduplication: true - subscribers: - - { endpoint: http://example1.com/, protocol: http } - - { endpoint: http://example2.com/, protocol: http } - -Note that `FIFO` queues are not currently compatible with `push_notifications`. For more information, see: http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-subscribe-queue-sns-topic.html diff --git a/docs/console-commands.rst b/docs/console-commands.rst deleted file mode 100644 index c769bee..0000000 --- a/docs/console-commands.rst +++ /dev/null @@ -1,43 +0,0 @@ -Console Commands -================ - -This bundle includes some Console Commands which can be used for building, destroying and polling your queues -as well as sending simple messages. - -Build Command -------------- - -You can use the ``uecode:qpush:build`` command to create the queues on your providers. You can specify the name of a queue -as an argument to build a single queue. This command will also warm cache which avoids the need to query the provider's API -to ensure that the queue exists. Most queue providers create commands are idempotent, so running this multiple times is not an issue.:: - - $ php app/console uecode:qpush:build my_queue_name - -**Note:** *By default, this bundle uses File Cache. If you clear cache, it is highly recommended you re-run the build command to warm the cache!* - -Destroy Command ---------------- - -You can use the ``uecode:qpush:destroy`` command to completely remove queues. You can specify the name of a queue as an argument to destroy -a single queue. If you do not specify an argument, this will destroy all queues after confirmation.:: - - $ php app/console uecode:qpush:destroy my_queue_name - -**Note:** *This will remove queues, even if there are still unreceived messages in the queue!* - -Receive Command ---------------- - -You can use the ``uecode:qpush:receive`` command to poll the specified queue. This command takes the name of a queue as an argument. -Messages received from this command are dispatched through the ``EventDispatcher`` and can be handled by your tagged services the same -as Push Notifications would be.:: - - $ php app/console uecode:qpush:receive my_queue_name - -Publish Command ---------------- - -You can use the ``uecode:qpush:publish`` command to send messages to your queue from the CLI. This command takes two arguments, the name of -the queue and the message to publish. The message needs to be a json encoded string.:: - - $ php app/console uecode:qpush:publish my_queue_name '{"foo": "bar"}' diff --git a/docs/custom-provider.rst b/docs/custom-provider.rst deleted file mode 100644 index aba3c1a..0000000 --- a/docs/custom-provider.rst +++ /dev/null @@ -1,23 +0,0 @@ -Custom Provider -------------- - -The custom provider allows you to use your own provider. When using this provider, your implementation must implement -``Uecode\Bundle\QPushBundle\Provider\ProviderInterface`` - -Configuration -^^^^^^^^^^^^^ - -To designate a queue as custom, set the ``driver`` of its provider to ``custom``, and the ``service`` to your service id. - -.. code-block:: yaml - - #app/config_dev.yml - - uecode_qpush: - providers: - custom_provider: - driver: custom - service: YOUR_CUSTOM_SERVICE_ID - queues: - my_queue_name: - provider: custom_provider \ No newline at end of file diff --git a/docs/file-provider.rst b/docs/file-provider.rst deleted file mode 100644 index 23dae24..0000000 --- a/docs/file-provider.rst +++ /dev/null @@ -1,23 +0,0 @@ -File Provider -------------- - -The file provider uses the filesystem to dispatch and resolve queued messages. - -Configuration -^^^^^^^^^^^^^ - -To designate a queue as file, set the ``driver`` of its provider to ``file``. You will -need to configure a readable and writable path to store the messages. - -.. code-block:: yaml - - #app/config_dev.yml - - uecode_qpush: - providers: - file_based: - driver: file - path: [Path to store messages] - queues: - my_queue_name: - provider: file_based \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst deleted file mode 100644 index b4ae69f..0000000 --- a/docs/index.rst +++ /dev/null @@ -1,24 +0,0 @@ -Overview -======== - -The QPush Bundle relies on the Push Queue model of Message Queues to provide asynchronous -processing in your Symfony application. This allows you to remove blocking processes from the -immediate flow of your application and delegate them to another part of your application or, say, a -cluster of workers. - -This bundle allows you to easily consume and process messages by simply tagging your service or -services and relying on Symfony's event dispatcher - without needing to run a daemon or background -process to continuously poll your queue. - -Content -======== - -.. toctree:: - :maxdepth: 4 - - installation - configuration - usage - console-commands - - diff --git a/docs/installation.rst b/docs/installation.rst deleted file mode 100644 index ad0bfdc..0000000 --- a/docs/installation.rst +++ /dev/null @@ -1,25 +0,0 @@ -Installation -============ - -**The bundle should be installed through composer.** - - :: - - composer require uecode/qpush-bundle - -**Update AppKernel.php of your Symfony Application** - -Add the ``UecodeQPushBundle`` to your kernel bootstrap sequence, in the ``$bundles`` array - -.. code-block:: php - - public function registerBundles() - { - $bundles = array( - // ... - new Uecode\Bundle\QPushBundle\UecodeQPushBundle(), - ); - - return $bundles; - } - diff --git a/docs/iron-mq-provider.rst b/docs/iron-mq-provider.rst deleted file mode 100644 index cae2ad7..0000000 --- a/docs/iron-mq-provider.rst +++ /dev/null @@ -1,130 +0,0 @@ -IronMQ Provider ---------------- - -The IronMQ Provider uses its Push Queues to notify subscribers of new queued -messages without needing to continually poll the queue. - -Using a Push Queue is optional with this provider and its possible to use simple -Pull queues by utilizing the provided Console Command (``uecode:qpush::receive``) -to poll the queue. - -Configuration -^^^^^^^^^^^^^ - -This provider relies on the `Iron MQ `_ classes -and needs to have the library included in your ``composer.json`` file. - -.. code-block:: js - - { - require: { - "iron-io/iron_mq": "^4.0" - } - } - - -Configuring the provider is very easy. It requires that you have already created -an account and have a project id. - -`Iron.io `_ provides free accounts for Development, which makes -testing and using this service extremely easy. - -Just include your OAuth `token` and `project_id` in the configuration and set your -queue to use a provider using the `ironmq` driver. - -.. code-block:: yaml - - #app/config.yml - - uecode_qpush: - providers: - my_provider: - driver: ironmq - token: YOUR_TOKEN_HERE - project_id: YOUR_PROJECT_ID_HERE - host: YOUR_OPTIONAL_HOST_HERE - port: YOUR_OPTIONAL_PORT_HERE - version_id: YOUR_OPTIONAL_VERSION_HERE - queues: - my_queue_name: - provider: my_provider - options: - push_notifications: true - subscribers: - - { endpoint: http://example.com/qpush, protocol: http } - -IronMQ Push Queues -^^^^^^^^^^^^^^^^^^ - -If you set ``push_notifications`` to ``true`` in your queue config, this provider -will automatically create your Queue as a Push Queue and loop over your list of ``subscribers``, -adding them to your Queue. - -This provider only supports ``http`` and ``https`` subscribers. This provider also uses the -``multicast`` setting for its Push Queues, meaning that all ``subscribers`` are notified of -the same new messages. - -You can chose to have your IronMQ queues work as a Pull Queue by setting ``push_notifications`` to ``false``. -This would require you to use the ``uecode:qpush:receive`` Console Command to poll the queue. - -Overriding Queue Options -^^^^^^^^^^^^^^^^^^^^^^^^ - -It's possible to override the default queue options that are set in your config file -when sending or receiving messages. - -**Publishing** - -The ``publish()`` method takes an array as a second argument. For the IronMQ -Provider you are able to change the options listed below per publish. - -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ -| Option | Description | Default Value | -+==========================+===========================================================================================+===============+ -| ``message_delay`` | Time in seconds before a published Message is available to be read in a Queue | ``0`` | -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ -| ``message_timeout`` | Time in seconds a worker has to delete a Message before it is available to other workers | ``30`` | -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ -| ``message_expiration`` | Time in seconds that Messages may remain in the Queue before being removed | ``604800`` | -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ - -.. code-block:: php - - $message = ['foo' => 'bar']; - - // Optional config to override default options - $options = [ - 'message_delay' => 1, - 'message_timeout' => 1, - 'message_expiration' => 60 - ]; - - $this->get('uecode_qpush.my_queue_name')->publish($message, $options); - - -**Receiving** - -The ``receive()`` method takes an array as a second argument. For the AWS Provider -you are able to change the options listed below per attempt to receive messages. - -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ -| Option | Description | Default Value | -+==========================+===========================================================================================+===============+ -| ``messages_to_receive`` | Maximum amount of messages that can be received when polling the queue | ``1`` | -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ -| ``message_timeout`` | Time in seconds a worker has to delete a Message before it is available to other workers | ``30`` | -+--------------------------+-------------------------------------------------------------------------------------------+---------------+ - -.. code-block:: php - - // Optional config to override default options - $options = [ - 'messages_to_receive' => 3, - 'message_timeout' => 10 - ]; - - $messages = $this->get('uecode_qpush.my_queue_name')->receive($options); - - foreach ($messages as $message) { - echo $message->getBody(); - } diff --git a/docs/sync-provider.rst b/docs/sync-provider.rst deleted file mode 100644 index 85e0046..0000000 --- a/docs/sync-provider.rst +++ /dev/null @@ -1,24 +0,0 @@ -Sync Provider -------------- - -The sync provider immediately dispatches and resolves queued events. It is not intended -for production use but instead to support local development, debugging and testing -of queue-based code paths. - -Configuration -^^^^^^^^^^^^^ - -To designate a queue as synchronous, set the ``driver`` of its provider to ``sync``. No further -configuration is necessary. - -.. code-block:: yaml - - #app/config_dev.yml - - uecode_qpush: - providers: - in_band: - driver: sync - queues: - my_queue_name: - provider: in_band \ No newline at end of file diff --git a/docs/usage.rst b/docs/usage.rst deleted file mode 100644 index d5d9df0..0000000 --- a/docs/usage.rst +++ /dev/null @@ -1,182 +0,0 @@ -Usage -===== - -Once configured, you can create messages and publish them to the queue. You may also -create services that will automatically be fired as messages are pushed to your application. - -For your convenience, a custom ``Provider`` service will be created and registered -in the Container for each of your defined Queues. The container queue service id will be -in the format of ``uecode_qpush.{your queue name}``. - -Publishing messages to your Queue ---------------------------------- - -Publishing messages is simple - fetch your ``Provider`` service from the container and -call the ``publish`` method on the respective queue, which accepts an array. - -.. code-block:: php - - #src/My/Bundle/ExampleBundle/Controller/MyController.php - - public function publishAction() - { - $message = [ - 'messages should be an array', - 'they can be flat arrays' => [ - 'or multidimensional' - ] - ]; - - $this->get('uecode_qpush.my_queue_name')->publish($message); - } - -Working with messages from your Queue -------------------------------------- - -Messages are either automatically received by your application and events dispatched -(setting ``push_notification`` to ``true``), or can be picked up by Cron jobs through an included -command if you are not using a Message Queue provider that supports Push notifications. - -When the notifications or messages are Pushed to your application, the QPush Bundle automatically -catches the request and dispatches an event which can be easily hooked into. - -MessageEvents -^^^^^^^^^^^^^ - -Once a message is received via POST from your Message Queue, a ``MessageEvent`` is dispatched -which can be handled by your services. Each ``MessageEvent`` contains the name of the queue -and a ``Uecode\Bundle\QPushBundle\Message\Message`` object, accessible through getters. - -.. code-block:: php - - #src/My/Bundle/ExampleBundle/Service/ExampleService.php - - use Uecode\Bundle\QPushBundle\Event\MessageEvent - - public function onMessageReceived(MessageEvent $event) - { - $queue_name = $event->getQueueName(); - $message = $event->getMessage(); - } - -The ``Message`` objects contain the provider specific message id, a message body, -and a collection of provider specific metadata. - -These properties are accessible through simple getters. - -The message ``body`` is an array matching your original message. The ``metadata`` property is an -``ArrayCollection`` of varying fields sent with your message from your Queue Provider. - -.. code-block:: php - - #src/My/Bundle/ExampleBundle/Service/ExampleService.php - - use Uecode\Bundle\QPushBundle\Event\MessageEvent; - use Uecode\Bundle\QPushBundle\Message\Message; - - public function onMessageReceived(MessageEvent $event) - { - $id = $event->getMessage()->getId(); - $body = $event->getMessage()->getBody(); - $metadata = $event->getMessage()->getMetadata(); - - // do some processing - } - -Tagging Your Services -^^^^^^^^^^^^^^^^^^^^^ - -For your Services to be called on QPush events, they must be tagged with the name -``uecode_qpush.event_listener``. A complete tag is made up of the following properties: - -============ ================================= ========================================================================================== -Tag Property Example Description -============ ================================= ========================================================================================== -``name`` ``uecode_qpush.event_listener`` The Qpush Event Listener Tag -``event`` ``{queue name}.message_received`` The `message_received` event, prefixed with the Queue name -``method`` ``onMessageReceived`` A publicly accessible method on your service -``priority`` ``100`` Priority, ``1``-``100`` to control order of services. Higher priorities are called earlier -============ ================================= ========================================================================================== - -The ``priority`` is useful to chain services, ensuring that they fire in a certain order - the higher priorities fire earlier. - -Each event fired by the Qpush Bundle is prefixed with the name of your queue, ex: ``my_queue_name.message_received``. - -This allows you to assign services to fire only on certain queues, based on the queue name. -However, you may also have multiple tags on a single service, so that one service can handle -events from multiple queues. - -.. code-block:: yaml - - services: - my_example_service: - class: My\Example\ExampleService - tags: - - { name: uecode_qpush.event_listener, event: my_queue_name.message_received, method: onMessageReceived } - -The method listed in the tag must be publicly available in your service and should -take a single argument, an instance of ``Uecode\Bundle\QPushBundle\Event\MessageEvent``. - -.. code-block:: php - - #src/My/Bundle/ExampleBundle/Service/MyService.php - - use Uecode\Bundle\QPushBundle\Event\MessageEvent; - - // ... - - public function onMessageReceived(MessageEvent $event) - { - $queueName = $event->getQueueName(); - $message = $event->getMessage(); - $metadata = $message()->getMetadata(); - - // Process ... - } - -Cleaning Up the Queue ---------------------- - -Once all other Event Listeners have been invoked on a ``MessageEvent``, the QPush Bundle -will automatically attempt to remove the Message from your Queue for you. - -If an error or exception is thrown, or event propagation is stopped earlier in the chain, -the Message will not be removed automatically and may be picked up by other workers. - -If you would like to remove the message inside your service, you can do so by calling the ``delete`` -method on your provider and passing it the message ``id``. However, you must also stop -the event propagation to avoid other services (including the Provider service) from firing on that -``MessageEvent``. - -.. code-block:: php - - #src/My/Bundle/ExampleBundle/Service/MyService.php - - use Uecode\Bundle\QPushBundle\Event\MessageEvent; - - // ... - - public function onMessageReceived(MessageEvent $event) - { - $id = $event->getMessage()->getId(); - // Removes the message from the queue - $awsProvider->delete($id); - - // Stops the event from propagating - $event->stopPropagation(); - } - -Push Queues in Development --------------------------- - -It is recommended to use your ``config_dev.yml`` file to disable the -``push_notifications`` settings on your queues. This will make the queue a simple -Pull queue. You can then use the ``uecode:qpush:receive`` Console Command to receive -messages from your Queue. - -If you need to test the Push Queue functionality from a local stack or internal -machine, it's possible to use `ngrok `_ to tunnel to your development -environment, so its reachable by your Queue Provider. - -You would need to update your `config_dev.yml` configuration to use the `ngrok` url for -your subscriber(s). diff --git a/integration_tests/Provider/IronMqProviderTest.php b/integration_tests/Provider/IronMqProviderTest.php deleted file mode 100755 index 6f8359c..0000000 --- a/integration_tests/Provider/IronMqProviderTest.php +++ /dev/null @@ -1,205 +0,0 @@ -client = new IronMQ([ - 'token' => IRONMQ_TOKEN, - 'project_id' => IRONMQ_PROJECT_ID, - 'host' => IRONMQ_HOST - ]); - - $this->provider = $this->getIronMqProvider(); - } - - public function tearDown(): void - { - if (!is_null($this->provider)) { - $this->provider->destroy(); - $this->provider = null; - } - } - - private function getIronMqProvider(array $options = []) - { - $options = array_merge( - [ - 'logging_enabled' => false, - 'push_notifications' => true, - 'push_type' => 'multicast', - 'notification_retries' => 3, - 'notification_retries_delay' => 60, - 'message_delay' => 0, - 'message_timeout' => 30, - 'message_expiration' => 604800, - 'messages_to_receive' => 1, - 'rate_limit' => -1, - 'receive_wait_time' => 3, - 'subscribers' => [ - [ 'protocol' => 'http', 'endpoint' => 'http://fake.com' ] - ] - ], - $options - ); - - return new IronMqProvider( - 'test', - $options, - $this->client, - $this->getMock( - 'Doctrine\Common\Cache\PhpFileCache', - [], - ['/tmp', 'qpush.ironmq.test.php'] - ), - $this->getMock( - 'Symfony\Bridge\Monolog\Logger', - [], - ['qpush.test'] - ) - ); - } - - public function testGetProviderReturnsTheNameOfTheProvider() - { - $provider = $this->provider->getProvider(); - - $this->assertEquals('IronMQ', $provider); - } - - public function testCreateWillCreateAQueue() - { - $this->assertFalse($this->provider->queueExists()); - $this->assertTrue($this->provider->create()); - $this->assertTrue($this->provider->queueExists()); - } - - public function testCreateFailsWithEmailTypeSubscriber() - { - $provider = $this->getIronMqProvider([ - 'subscribers' => [ - [ 'protocol' => 'email', 'endpoint' => 'test@foo.com' ] - ] - ]); - - $this->setExpectedException('InvalidArgumentException', 'IronMQ only supports `http` or `https` subscribers!'); - $provider->create(); - $this->assertTrue($this->provider->queueExists()); - - } - - public function testDestroyWillDestroyAQueue() - { - $this->provider->create(); - $this->assertTrue($this->provider->queueExists(), 'fail1'); - - $this->assertTrue($this->provider->destroy(), 'fail2'); - - $this->assertFalse($this->provider->queueExists(), 'fail3'); - - } - - public function testPublishWillPublishAMessage() - { - $message = $this->provider->publish(['foo' => 'bar']); - $this->assertInternalType("int", $message); - } - - public function testReceiveWillReserveAndReturnAMessageFromTheQueue() - { - $this->provider = $this->getIronMqProvider(['push_notifications' => false]); - $this->provider->publish(['baz' => 'bar']); - - $messages = $this->provider->receive(); - - $this->assertInternalType('array', $messages); - $this->assertCount(1, $messages); - $this->assertEquals(['baz' => 'bar'], $messages[0]->getBody()); - } - - public function testDeleteAnUnreservedMessage() - { - $messageId = $this->provider->publish(['bat' => 'ball']); - - $this->assertTrue($this->provider->delete($messageId)); - } - - public function testDeleteAReservedMessage() - { - $this->provider = $this->getIronMqProvider(['push_notifications' => false]); - $this->provider->publish(['Hello' => 'World']); - $messages = $this->provider->receive(); - - $this->assertTrue($this->provider->delete($messages[0]->getId())); - } - - public function testOnNotification() - { - $event = new NotificationEvent( - 'test', - NotificationEvent::TYPE_MESSAGE, - new Notification(123, "test", []) - ); - - $this->provider->onNotification( - $event, - NotificationEvent::TYPE_MESSAGE, - $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface') - ); - } - - public function testOnMessageReceived() - { - $this->provider = $this->getIronMqProvider(['push_notifications' => false]); - $this->provider->destroy(); - $this->provider->publish(['bob' => 'ball']); - $messages = $this->provider->receive(); - - $this->provider->onMessageReceived(new MessageEvent( - 'test', - $messages[0] - )); - } - - public function testQueueInfo() - { - $this->provider->destroy(); - $this->assertNull($this->provider->queueInfo()); - - $this->provider->create(); - $queue = $this->provider->queueInfo(); - $this->assertEquals('qpush_test', $queue->name); - $this->assertEquals(IRONMQ_PROJECT_ID, $queue->project_id); - } -} diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 2758e11..2b8f9b9 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -16,11 +16,6 @@ - - - - - ./tests/ diff --git a/src/Command/QueueDestroyCommand.php b/src/Command/QueueDestroyCommand.php index b512afb..763e6c4 100755 --- a/src/Command/QueueDestroyCommand.php +++ b/src/Command/QueueDestroyCommand.php @@ -61,7 +61,7 @@ protected function configure() { $this ->setName('uecode:qpush:destroy') - ->setDescription('Destroys the configured Queues and cleans Cache') + ->setDescription('Destroys the configured queues') ->addArgument( 'name', InputArgument::OPTIONAL, diff --git a/src/Command/QueueReceiveCommand.php b/src/Command/QueueReceiveCommand.php index 9b8822b..7e89ba3 100755 --- a/src/Command/QueueReceiveCommand.php +++ b/src/Command/QueueReceiveCommand.php @@ -103,7 +103,7 @@ private function pollQueue($registry, $name) if($messages) { foreach ($messages as $message) { $messageEvent = new MessageEvent($name, $message); - $dispatcher->dispatch(Events::Message($name), $messageEvent); + $dispatcher->dispatch($messageEvent, Events::Message($name)); } } diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index d5f65ed..ba1f7ac 100755 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -32,18 +32,11 @@ class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { - $treeBuilder = new TreeBuilder(); - $rootNode = $treeBuilder->root('uecode_qpush'); + $treeBuilder = new TreeBuilder('uecode_qpush'); - $rootNode + $treeBuilder->getRootNode() ->addDefaultsIfNotSet() ->children() - ->scalarNode('cache_service') - ->defaultNull() - ->end() - ->booleanNode('logging_enabled') - ->defaultTrue() - ->end() ->append($this->getProvidersNode()) ->append($this->getQueuesNode()) ->end() @@ -54,8 +47,7 @@ public function getConfigTreeBuilder() private function getProvidersNode() { - $treeBuilder = new TreeBuilder(); - $node = $treeBuilder->root('providers'); + $treeBuilder = new TreeBuilder('providers'); $requirements = [ 'aws' => [], 'ironmq' => ['token', 'project_id'], @@ -64,6 +56,7 @@ private function getProvidersNode() 'file' => ['path'], 'doctrine' => [] ]; + $node = $treeBuilder->getRootNode(); $node ->useAttributeAsKey('name') @@ -126,8 +119,8 @@ private function getProvidersNode() private function getQueuesNode() { - $treeBuilder = new TreeBuilder(); - $node = $treeBuilder->root('queues'); + $treeBuilder = new TreeBuilder('queues'); + $node = $treeBuilder->getRootNode(); $node ->requiresAtLeastOneElement() @@ -213,8 +206,8 @@ private function getQueuesNode() private function getSubscribersNode() { - $treeBuilder = new TreeBuilder(); - $node = $treeBuilder->root('subscribers'); + $treeBuilder = new TreeBuilder('subscribers'); + $node = $treeBuilder->getRootNode(); $node ->prototype('array') diff --git a/src/DependencyInjection/UecodeQPushExtension.php b/src/DependencyInjection/UecodeQPushExtension.php index af2d057..ac68106 100755 --- a/src/DependencyInjection/UecodeQPushExtension.php +++ b/src/DependencyInjection/UecodeQPushExtension.php @@ -58,13 +58,9 @@ public function load(array $configs, ContainerBuilder $container) $loader->load('services.yml'); $registry = $container->getDefinition('uecode_qpush.registry'); - $cache = $config['cache_service'] ?: 'uecode_qpush.file_cache'; foreach ($config['queues'] as $queue => $values) { - // Adds logging property to queue options - $values['options']['logging_enabled'] = $config['logging_enabled']; - $provider = $values['provider']; $class = null; $client = null; @@ -78,56 +74,14 @@ public function load(array $configs, ContainerBuilder $container) $provider ); break; - case 'ironmq': - $class = $container->getParameter('uecode_qpush.provider.ironmq'); - $client = $this->createIronMQClient( - $config['providers'][$provider], - $container, - $provider - ); - break; - case 'sync': - $class = $container->getParameter('uecode_qpush.provider.sync'); - $client = $this->createSyncClient(); - break; - case 'custom': - $class = $container->getParameter('uecode_qpush.provider.custom'); - $client = $this->createCustomClient($config['providers'][$provider]['service']); - break; - case 'file': - $class = $container->getParameter('uecode_qpush.provider.file'); - $values['options']['path'] = $config['providers'][$provider]['path']; - break; - case 'doctrine': - $class = $container->getParameter('uecode_qpush.provider.doctrine'); - $client = $this->createDoctrineClient($config['providers'][$provider]); - break; } $definition = new Definition( - $class, [$queue, $values['options'], $client, new Reference($cache), new Reference('logger')] + $class, [$queue, $values['options'], $client] ); $definition->setPublic(true); - $definition->addTag('monolog.logger', ['channel' => 'qpush']) - ->addTag( - 'uecode_qpush.event_listener', - [ - 'event' => "{$queue}.on_notification", - 'method' => "onNotification", - 'priority' => 255 - ] - ) - ->addTag( - 'uecode_qpush.event_listener', - [ - 'event' => "{$queue}.message_received", - 'method' => "onMessageReceived", - 'priority' => -255 - ] - ); - $isProviderAWS = $config['providers'][$provider]['driver'] === 'aws'; $isQueueNameSet = isset($values['options']['queue_name']) && !empty($values['options']['queue_name']); diff --git a/src/Entity/DoctrineMessage.php b/src/Entity/DoctrineMessage.php deleted file mode 100644 index 5dee4a9..0000000 --- a/src/Entity/DoctrineMessage.php +++ /dev/null @@ -1,236 +0,0 @@ -id; - } - - /** - * Set message - * - * @param array $message - * - * @return DoctrineMessage - */ - public function setMessage($message) - { - $this->message = $message; - - return $this; - } - - /** - * Get message - * - * @return array - */ - public function getMessage() - { - return $this->message; - } - - /** - * Set queue - * - * @param string $queue - * - * @return DoctrineMessage - */ - public function setQueue($queue) - { - $this->queue = $queue; - - return $this; - } - - /** - * Get queue - * - * @return string - */ - public function getQueue() - { - return $this->queue; - } - - /** - * Set delivered - * - * @param boolean $delivered - * - * @return DoctrineMessage - */ - public function setDelivered($delivered) - { - $this->delivered = $delivered; - - return $this; - } - - /** - * Get delivered - * - * @return boolean - */ - public function getDelivered() - { - return $this->delivered; - } - - /** - * Set created - * - * @param \DateTime $created - * - * @return DoctrineMessage - */ - public function setCreated($created) - { - $this->created = $created; - - return $this; - } - - /** - * Get created - * - * @return \DateTime - */ - public function getCreated() - { - return $this->created; - } - - /** - * Set updated - * - * @param \DateTime $updated - * - * @return DoctrineMessage - */ - public function setUpdated($updated) - { - $this->updated = $updated; - - return $this; - } - - /** - * Get updated - * - * @return \DateTime - */ - public function getUpdated() - { - return $this->updated; - } - - /** - * Set length - * - * @param integer $length - * - * @return DoctrineMessage - */ - public function setLength($length) - { - $this->length = $length; - - return $this; - } - - /** - * Get length - * - * @return integer - */ - public function getLength() - { - return $this->length; - } -} diff --git a/src/EventListener/RequestListener.php b/src/EventListener/RequestListener.php index 2fc8ad8..c170090 100644 --- a/src/EventListener/RequestListener.php +++ b/src/EventListener/RequestListener.php @@ -101,8 +101,8 @@ private function handleIronMqNotifications(GetResponseEvent $event) { ); $this->dispatcher->dispatch( - Events::Notification($queue), - new NotificationEvent($queue, NotificationEvent::TYPE_MESSAGE, $notification) + new NotificationEvent($queue, NotificationEvent::TYPE_MESSAGE, $notification), + Events::Notification($queue) ); return "IronMQ Notification Received."; @@ -138,8 +138,8 @@ private function handleSnsNotifications(GetResponseEvent $event) { ); $this->dispatcher->dispatch( - Events::Notification($queue), - new NotificationEvent($queue, NotificationEvent::TYPE_MESSAGE, $notification) + new NotificationEvent($queue, NotificationEvent::TYPE_MESSAGE, $notification), + Events::Notification($queue) ); return "SNS Message Notification Received."; @@ -161,8 +161,8 @@ private function handleSnsNotifications(GetResponseEvent $event) { ); $this->dispatcher->dispatch( - Events::Notification($queue), - new NotificationEvent($queue, NotificationEvent::TYPE_SUBSCRIPTION, $notification) + new NotificationEvent($queue, NotificationEvent::TYPE_SUBSCRIPTION, $notification), + Events::Notification($queue) ); return "SNS Subscription Confirmation Received."; diff --git a/src/Provider/AbstractProvider.php b/src/Provider/AbstractProvider.php index 3e9d834..7a46e6e 100755 --- a/src/Provider/AbstractProvider.php +++ b/src/Provider/AbstractProvider.php @@ -22,8 +22,6 @@ namespace Uecode\Bundle\QPushBundle\Provider; -use Doctrine\Common\Cache\Cache; -use Monolog\Logger; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Uecode\Bundle\QPushBundle\Event\MessageEvent; use Uecode\Bundle\QPushBundle\Event\NotificationEvent; @@ -47,20 +45,6 @@ abstract class AbstractProvider implements ProviderInterface */ protected $options; - /** - * Doctrine APC Cache Driver - * - * @var Cache - */ - protected $cache; - - /** - * Monolog Logger - * - * @var Logger - */ - protected $logger; - /** * {@inheritDoc} */ @@ -89,37 +73,6 @@ public function getOptions() return $this->options; } - /** - * {@inheritDoc} - */ - public function getCache() - { - return $this->cache; - } - - /** - * {@inheritDoc} - */ - public function getlogger() - { - return $this->logger; - } - - /** - * {@inheritDoc} - */ - public function log($level, $message, array $context = []) - { - if (!$this->options['logging_enabled']) { - return false; - } - - // Add the queue name and provider to the context - $context = array_merge(['queue' => $this->name, 'provider' => $this->getProvider()], $context); - - return $this->logger->addRecord($level, $message, $context); - } - /** * @param NotificationEvent $event * @param string $eventName Name of the event diff --git a/src/Provider/AwsProvider.php b/src/Provider/AwsProvider.php index c158cf1..c116a4b 100755 --- a/src/Provider/AwsProvider.php +++ b/src/Provider/AwsProvider.php @@ -27,8 +27,6 @@ use Aws\Sqs\Exception\SqsException; use Aws\Sqs\SqsClient; -use Doctrine\Common\Cache\Cache; -use Monolog\Logger; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Uecode\Bundle\QPushBundle\Event\Events; use Uecode\Bundle\QPushBundle\Event\MessageEvent; @@ -72,15 +70,11 @@ class AwsProvider extends AbstractProvider * @param string $name * @param array $options * @param mixed $client - * @param Cache $cache - * @param Logger $logger */ - public function __construct($name, array $options, $client, Cache $cache, Logger $logger) + public function __construct($name, array $options, $client) { $this->name = $name; $this->options = $options; - $this->cache = $cache; - $this->logger = $logger; // get() method used for sdk v2, create methods for v3 $useGet = method_exists($client, 'get'); @@ -140,21 +134,13 @@ public function create() */ public function destroy() { - $key = $this->getNameWithPrefix() . '_url'; - $this->cache->delete($key); - if ($this->queueExists()) { // Delete the SQS Queue $this->sqs->deleteQueue([ 'QueueUrl' => $this->queueUrl ]); - - $this->log(200,"SQS Queue removed", ['QueueUrl' => $this->queueUrl]); } - $key = $this->getNameWithPrefix() . '_arn'; - $this->cache->delete($key); - if ($this->topicExists() || !empty($this->queueUrl)) { // Delete the SNS Topic $topicArn = !empty($this->topicArn) @@ -165,8 +151,6 @@ public function destroy() $this->sns->deleteTopic([ 'TopicArn' => $topicArn ]); - - $this->log(200,"SNS Topic removed", ['TopicArn' => $topicArn]); } return true; @@ -202,11 +186,6 @@ public function publish(array $message, array $options = []) } if ($options['push_notifications']) { - - if (!$this->topicExists()) { - $this->create(); - } - $message = [ 'default' => $this->getNameWithPrefix(), 'sqs' => json_encode($message), @@ -221,14 +200,6 @@ public function publish(array $message, array $options = []) 'MessageStructure' => 'json' ]); - $context = [ - 'TopicArn' => $this->topicArn, - 'MessageId' => $result->get('MessageId'), - 'push_notifications' => $options['push_notifications'], - 'publish_time' => microtime(true) - $publishStart - ]; - $this->log(200,"Message published to SNS", $context); - return $result->get('MessageId'); } @@ -255,13 +226,6 @@ public function publish(array $message, array $options = []) $result = $this->sqs->sendMessage($arguments); - $context = [ - 'QueueUrl' => $this->queueUrl, - 'MessageId' => $result->get('MessageId'), - 'push_notifications' => $options['push_notifications'], - 'fifo' => $options['fifo'] - ]; - if ($this->isQueueFIFO()) { if (isset($arguments['MessageDeduplicationId'])) { $context['message_deduplication_id'] = $arguments['MessageDeduplicationId']; @@ -269,8 +233,6 @@ public function publish(array $message, array $options = []) $context['message_group_id'] = $arguments['MessageGroupId']; } - $this->log(200,"Message published to SQS", $context); - return $result->get('MessageId'); } @@ -309,10 +271,6 @@ public function receive(array $options = []) } $message = new Message($id, $body, $metadata); - - $context = ['MessageId' => $id]; - $this->log(200,"Message fetched from SQS Queue", $context); - } return $messages; @@ -334,21 +292,14 @@ public function delete($id) 'ReceiptHandle' => $id ]); - $context = [ - 'QueueUrl' => $this->queueUrl, - 'ReceiptHandle' => $id - ]; - $this->log(200,"Message deleted from SQS Queue", $context); - return true; } /** * Return the Queue Url * - * This method relies on in-memory cache and the Cache provider - * to reduce the need to needlessly call the create method on an existing - * Queue. + * This method relies on in-memory cache to reduce the need to needlessly + * call the create method on an existing Queue. * * @return boolean */ @@ -358,13 +309,6 @@ public function queueExists() return true; } - $key = $this->getNameWithPrefix() . '_url'; - if ($this->cache->contains($key)) { - $this->queueUrl = $this->cache->fetch($key); - - return true; - } - try { $result = $this->sqs->getQueueUrl([ 'QueueName' => $this->getNameWithPrefix() @@ -372,7 +316,6 @@ public function queueExists() $this->queueUrl = $result->get('QueueUrl'); if ($this->queueUrl !== null) { - $this->cache->save($key, $this->queueUrl); return true; } @@ -381,6 +324,41 @@ public function queueExists() return false; } + /** + * Checks to see if a Topic exists + * + * This method relies on in-memory cache to reduce the need to needlessly + * call the create method on an existing Topic. + * + * @return boolean + */ + public function topicExists() + { + if (isset($this->topicArn)) { + return true; + } + + if (!empty($this->queueUrl)) { + $queueArn = $this->sqs->getQueueArn($this->queueUrl); + $topicArn = str_replace('sqs', 'sns', $queueArn); + + try { + $this->sns->getTopicAttributes([ + 'TopicArn' => $topicArn + ]); + } catch (SnsException $e) { + return false; + } + + $this->topicArn = $topicArn; + + return true; + } + + return false; + } + + /** * Creates an SQS Queue and returns the Queue Url * @@ -406,11 +384,6 @@ public function createQueue() $this->queueUrl = $result->get('QueueUrl'); - $key = $this->getNameWithPrefix() . '_url'; - $this->cache->save($key, $this->queueUrl); - - $this->log(200, "Created SQS Queue", ['QueueUrl' => $this->queueUrl]); - if ($this->options['push_notifications']) { $policy = $this->createSqsPolicy(); @@ -421,8 +394,6 @@ public function createQueue() 'Policy' => $policy, ] ]); - - $this->log(200, "Created Updated SQS Policy"); } } @@ -450,49 +421,6 @@ public function createSqsPolicy() ]); } - /** - * Checks to see if a Topic exists - * - * This method relies on in-memory cache and the Cache provider - * to reduce the need to needlessly call the create method on an existing - * Topic. - * - * @return boolean - */ - public function topicExists() - { - if (isset($this->topicArn)) { - return true; - } - - $key = $this->getNameWithPrefix() . '_arn'; - if ($this->cache->contains($key)) { - $this->topicArn = $this->cache->fetch($key); - - return true; - } - - if (!empty($this->queueUrl)) { - $queueArn = $this->sqs->getQueueArn($this->queueUrl); - $topicArn = str_replace('sqs', 'sns', $queueArn); - - try { - $this->sns->getTopicAttributes([ - 'TopicArn' => $topicArn - ]); - } catch (SnsException $e) { - return false; - } - - $this->topicArn = $topicArn; - $this->cache->save($key, $this->topicArn); - - return true; - } - - return false; - } - /** * Creates a SNS Topic and returns the ARN * @@ -515,11 +443,6 @@ public function createTopic() $this->topicArn = $result->get('TopicArn'); - $key = $name . '_arn'; - $this->cache->save($key, $this->topicArn); - - $this->log(200, "Created SNS Topic", ['TopicARN' => $this->topicArn]); - return true; } @@ -566,13 +489,6 @@ public function subscribeToTopic($topicArn, $protocol, $endpoint) $arn = $result->get('SubscriptionArn'); - $context = [ - 'Endpoint' => $endpoint, - 'Protocol' => $protocol, - 'SubscriptionArn' => $arn - ]; - $this->log(200, "Endpoint Subscribed to SNS Topic", $context); - return $arn; } @@ -598,13 +514,6 @@ public function unsubscribeFromTopic($topicArn, $protocol, $endpoint) 'SubscriptionArn' => $subscription['SubscriptionArn'] ]); - $context = [ - 'Endpoint' => $endpoint, - 'Protocol' => $protocol, - 'SubscriptionArn' => $subscription['SubscriptionArn'] - ]; - $this->log(200,"Endpoint unsubscribed from SNS Topic", $context); - return true; } } @@ -638,17 +547,13 @@ public function onNotification(NotificationEvent $event, $eventName, EventDispat 'Token' => $token ]); - $context = ['TopicArn' => $topicArn]; - $this->log(200,"Subscription to SNS Confirmed", $context); - return; } $messages = $this->receive(); foreach ($messages as $message) { - $messageEvent = new MessageEvent($this->name, $message); - $dispatcher->dispatch(Events::Message($this->name), $messageEvent); + $dispatcher->dispatch($messageEvent, Events::Message($this->name)); } } diff --git a/src/Provider/CustomProvider.php b/src/Provider/CustomProvider.php deleted file mode 100755 index 71cda6a..0000000 --- a/src/Provider/CustomProvider.php +++ /dev/null @@ -1,125 +0,0 @@ - - */ -class CustomProvider extends AbstractProvider -{ - /** - * @type ProviderInterface - */ - private $client; - - /** - * @param string $name - * @param array $options - * @param mixed $client - * @param Cache $cache - * @param Logger $logger - */ - public function __construct($name, array $options, $client, Cache $cache, Logger $logger) - { - $this->name = $name; - $this->options = $options; - $this->cache = $cache; - $this->logger = $logger; - - $this->setClient($client); - } - - /** - * @param ProviderInterface $client - * - * @return CustomProvider - */ - public function setClient(ProviderInterface $client) - { - $this->client = $client; - - return $this; - } - - public function getProvider() - { - return 'Custom'; - } - - /** - * Builds the configured queues - * - * If a Queue name is passed and configured, this method will build only that - * Queue. - * - * All Create methods are idempotent, if the resource exists, the current ARN - * will be returned - * - */ - public function create() - { - return $this->client->create(); - } - - /** - * @return Boolean - */ - public function destroy() - { - return $this->client->destroy(); - } - - /** - * {@inheritDoc} - * - * This method will either use a SNS Topic to publish a queued message or - * straight to SQS depending on the application configuration. - * - * @return string - */ - public function publish(array $message, array $options = []) - { - return $this->client->publish($message, $options); - } - - /** - * {@inheritDoc} - */ - public function receive(array $options = []) - { - return $this->client->receive($options); - } - - /** - * {@inheritDoc} - * - * @return bool - */ - public function delete($id) - { - return $this->client->delete($id); - } -} diff --git a/src/Provider/DoctrineProvider.php b/src/Provider/DoctrineProvider.php deleted file mode 100644 index cbd66c4..0000000 --- a/src/Provider/DoctrineProvider.php +++ /dev/null @@ -1,301 +0,0 @@ -name = $name; - $this->options = $options; - $this->cache = $cache; - $this->logger = $logger; - $this->em = $client; - $this->repository = $this->em->getRepository(self::$entityName); - } - - /** - * Returns the name of the Queue that this Provider is for - * - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * Returns the Queue Provider name - * - * @return string - */ - public function getProvider() - { - return 'Doctrine'; - } - - /** - * Returns the Provider's Configuration Options - * - * @return array - */ - public function getOptions() - { - return $this->options; - } - - /** - * Returns the Cache service - * - * @return Cache - */ - public function getCache() - { - return $this->cache; - } - - /** - * Returns the Logger service - * - * @return Logger - */ - public function getLogger() - { - return $this->logger; - } - - /** - * Get repository - * - * @return array - */ - public function getRepository() - { - if (!$this->repository) { - return; - } - - return $this->repository; - } - - /** - * Creates the Queue - * Checks to see if the underlying table has been created or not - * - * @return bool - */ - public function create() - { - $sm = $this->em->getConnection()->getSchemaManager(); - $table = $this->em->getClassMetadata(self::$entityName)->getTableName(); - - return $sm->tablesExist(array($table)); - } - - /** - * Publishes a message to the Queue - * - * This method should return a string MessageId or Response - * - * @param array $message The message to queue - * @param array $options An array of options that override the queue defaults - * - * @return string - */ - public function publish(array $message, array $options = []) - { - if (!$this->em) { - return ''; - } - - $doctrineMessage = new DoctrineMessage(); - $doctrineMessage->setQueue($this->name) - ->setDelivered(false) - ->setMessage($message) - ->setLength(strlen(serialize($message))); - - $this->em->persist($doctrineMessage); - $this->em->flush(); - - return (string) $doctrineMessage->getId(); - } - - /** - * Polls the Queue for Messages - * - * Depending on the Provider, this method may keep the connection open for - * a configurable amount of time, to allow for long polling. In most cases, - * this method is not meant to be used to long poll indefinitely, but should - * return in reasonable amount of time - * - * @param array $options An array of options that override the queue defaults - * - * @return array - */ - public function receive(array $options = []) - { - if (!$this->em) { - return []; - } - - $doctrineMessages = $this->repository->findBy( - array('delivered' => false, 'queue' => $this->name), array('id' => 'ASC') - ); - - $messages = []; - foreach ($doctrineMessages as $doctrineMessage) { - $messages[] = new Message($doctrineMessage->getId(), $doctrineMessage->getMessage(), []); - $doctrineMessage->setDelivered(true); - } - $this->em->flush(); - - return $messages; - } - - /** - * Deletes the Queue Message - * - * @param mixed $id A message identifier or resource - */ - public function delete($id) - { - $doctrineMessage = $this->repository->findById($id); - $doctrineMessage->setDelivered(true); - $this->em->flush(); - - return true; - } - - /** - * Destroys a Queue and clears any Queue related Cache - * - * @return bool - */ - public function destroy() - { - $qb = $this->repository->createQueryBuilder('dm'); - $qb->delete(); - $qb->where('dm.queue = :queue'); - $qb->setParameter('queue', $this->name); - $qb->getQuery()->execute(); - - return true; - } - - /** - * Returns a specific message - * - * @param integer $id - * - * @return Message - */ - public function getById($id) - { - return $this->repository->find($id); - } - - /** - * Returns a query of the message queue - * - * @param array $data ['field'=>'id', 'search'=>'text', 'to'=>date, from=>date] - * @return Query - * - */ - public function findBy($data) - { - $qb = $this->repository->createQueryBuilder('p'); - $qb->select('p'); - $qb->where('p.queue = :queue'); - $qb->setParameter('queue', $this->name); - - $field = (isset($data['field'])) ? $data['field'] : 'message'; - - if (isset($data['search']) && $data['search'] !== null) { - $qb->andWhere('p.' . $field . ' LIKE :contains'); - $qb->setParameter('contains', '%' . $data['search'] . '%'); - } - - if (isset($data['from']) && $data['from'] !== null && isset($data['to']) && $data['to'] !== null) { - $qb->andWhere('p.created BETWEEN :from AND :to'); - $qb->setParameter('from', $data['from']); - $qb->setParameter('to', $data['to']); - } - - return $qb->getQuery(); - } - - /* - * Returns an array of times and messgae counts - * @praram $data ['from' => date, 'to' => date, 'period' => seconds - * @return ['time', 'count'] - */ - - public function counts($data=null) - { - if (isset($data['period']) && $data['period'] !== null) { - $period = $data['period']; - } else { - $period = self::DEFAULT_PERIOD; - } - $sql = 'SELECT from_unixtime(floor(unix_timestamp(created)/' - . $period . ') * ' . $period . ') as time, - count(*) as count - FROM uecode_qpush_message - where queue = "' . $this->name . '"'; - if (isset($data['from']) && $data['from'] !== null) { - $sql = $sql . ' and created >= "' . $data['from'] . '"'; - } - if (isset($data['to']) && $data['to'] !== null) { - $sql = $sql . ' and created <= "' . $data['to'] . '"'; - } - $sql = $sql . ' group by floor(unix_timestamp(created)/' . $period . ')'; - $sql = $sql . ' order by floor(unix_timestamp(created)/' . $period . ') ASC'; - $statement = $this->em->getConnection()->prepare($sql); - $statement->execute(); - $results = $statement->fetchAll(); - - return $results; - } - -} diff --git a/src/Provider/FileProvider.php b/src/Provider/FileProvider.php deleted file mode 100644 index b97e1f6..0000000 --- a/src/Provider/FileProvider.php +++ /dev/null @@ -1,168 +0,0 @@ -name = $name; - /* md5 only contain numeric and A to F, so it is file system safe */ - $this->queuePath = $options['path'].DIRECTORY_SEPARATOR.str_replace('-', '', hash('md5', $name)); - $this->options = $options; - $this->cache = $cache; - $this->logger = $logger; - } - - public function getProvider() - { - return 'File'; - } - - public function create() - { - $fs = new Filesystem(); - if (!$fs->exists($this->queuePath)) { - $fs->mkdir($this->queuePath); - return $fs->exists($this->queuePath); - } - return true; - } - - public function publish(array $message, array $options = []) - { - $fileName = microtime(false); - $fileName = str_replace(' ', '', $fileName); - $path = substr(hash('md5', $fileName), 0, 3); - - $fs = new Filesystem(); - if (!$fs->exists($this->queuePath.DIRECTORY_SEPARATOR.$path)) { - $fs->mkdir($this->queuePath.DIRECTORY_SEPARATOR.$path); - } - - $fs->dumpFile( - $this->queuePath.DIRECTORY_SEPARATOR.$path.DIRECTORY_SEPARATOR.$fileName.'.json', - json_encode($message) - ); - return $fileName; - } - - /** - * @param array $options - * @return Message[] - */ - public function receive(array $options = []) - { - $finder = new Finder(); - $finder - ->files() - ->ignoreDotFiles(true) - ->ignoreUnreadableDirs(true) - ->ignoreVCS(true) - ->name('*.json') - ->in($this->queuePath) - ; - if ($this->options['message_delay'] > 0) { - $finder->date( - sprintf('< %d seconds ago', $this->options['message_delay']) - ); - } - $finder - ->date( - sprintf('> %d seconds ago', $this->options['message_expiration']) - ) - ; - $messages = []; - /** @var SplFileInfo $file */ - foreach ($finder as $file) { - $filePointer = fopen($file->getRealPath(), 'r+'); - $id = substr($file->getFilename(), 0, -5); - if (!isset($this->filePointerList[$id]) && flock($filePointer, LOCK_EX | LOCK_NB)) { - $this->filePointerList[$id] = $filePointer; - $messages[] = new Message($id, json_decode($file->getContents(), true), []); - } else { - fclose($filePointer); - } - if (count($messages) === (int) $this->options['messages_to_receive']) { - break; - } - } - return $messages; - } - - public function delete($id) - { - $success = false; - if (isset($this->filePointerList[$id])) { - $fileName = $id; - $path = substr(hash('md5', (string)$fileName), 0, 3); - $fs = new Filesystem(); - $fs->remove( - $this->queuePath . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $fileName . '.json' - ); - fclose($this->filePointerList[$id]); - unset($this->filePointerList[$id]); - $success = true; - } - if (rand(1,10) === 5) { - $this->cleanUp(); - } - return $success; - } - - public function cleanUp() - { - $finder = new Finder(); - $finder - ->files() - ->in($this->queuePath) - ->ignoreDotFiles(true) - ->ignoreUnreadableDirs(true) - ->ignoreVCS(true) - ->depth('< 2') - ->name('*.json') - ; - $finder->date( - sprintf('< %d seconds ago', $this->options['message_expiration']) - ); - /** @var SplFileInfo $file */ - foreach ($finder as $file) { - @unlink($file->getRealPath()); - } - } - - public function destroy() - { - $fs = new Filesystem(); - $fs->remove($this->queuePath); - $this->filePointerList = []; - return !is_dir($this->queuePath); - } - - /** - * Removes the message from queue after all other listeners have fired - * - * If an earlier listener has erred or stopped propagation, this method - * will not fire and the Queued Message should become visible in queue again. - * - * Stops Event Propagation after removing the Message - * - * @param MessageEvent $event The SQS Message Event - * @return bool|void - */ - public function onMessageReceived(MessageEvent $event) - { - $id = $event->getMessage()->getId(); - $this->delete($id); - $event->stopPropagation(); - } -} diff --git a/src/Provider/IronMqProvider.php b/src/Provider/IronMqProvider.php deleted file mode 100755 index 727a555..0000000 --- a/src/Provider/IronMqProvider.php +++ /dev/null @@ -1,406 +0,0 @@ - - */ -class IronMqProvider extends AbstractProvider -{ - /** - * IronMQ Client - * - * @var IronMQ - */ - private $ironmq; - - /** - * IronMQ Queue - * - * @var object - */ - private $queue; - - /** - * @var Message[] - */ - private $reservedMessages = []; - - public function __construct($name, array $options, $client, Cache $cache, Logger $logger) - { - $this->name = $name; - $this->options = $options; - $this->ironmq = $client; - $this->cache = $cache; - $this->logger = $logger; - } - - public function getProvider() - { - return "IronMQ"; - } - - /** - * {@inheritDoc} - */ - public function create() - { - if ($this->options['push_notifications']) { - $params = [ - 'type' => $this->options['push_type'], - 'push' => [ - 'rate_limit' => $this->options['rate_limit'], - 'retries' => $this->options['notification_retries'], - 'retries_delay' => $this->options['notification_retries_delay'], - 'subscribers' => [] - ] - ]; - - foreach ($this->options['subscribers'] as $subscriber) { - if ($subscriber['protocol'] == "email") { - throw new \InvalidArgumentException( - 'IronMQ only supports `http` or `https` subscribers!' - ); - } - - $params['push']['subscribers'][] = ['url' => $subscriber['endpoint']]; - } - - } else { - $params = ['type' => 'pull']; - } - - $queueName = $this->getNameWithPrefix(); - - $this->queue = $this->ironmq->createQueue($queueName, $params); - - $this->cache->save($queueName, json_encode($this->queue)); - - $this->log(200, "Queue has been created.", $params); - - return true; - } - - /** - * {@inheritDoc} - */ - public function destroy() - { - // Catch `queue not found` exceptions, throw the rest. - $queueName = $this->getNameWithPrefix(); - try { - $this->ironmq->deleteQueue($queueName); - $this->queue = null; - } catch ( \Exception $e) { - if (false !== strpos($e->getMessage(), "Queue not found")) { - $this->log(400, "Queue did not exist"); - } else { - throw $e; - } - } - - $this->cache->delete($queueName); - - $this->log(200, "Queue has been destroyed."); - - return true; - } - - /** - * {@inheritDoc} - * - * @return int - */ - public function publish(array $message, array $options = []) - { - $options = $this->mergeOptions($options); - $publishStart = microtime(true); - - if (!$this->queueExists()) { - $this->create(); - } - - $result = $this->ironmq->postMessage( - $this->getNameWithPrefix(), - json_encode($message + ['_qpush_queue' => $this->name]), - [ - 'timeout' => $options['message_timeout'], - 'delay' => $options['message_delay'], - 'expires_in' => $options['message_expiration'] - ] - ); - - $context = [ - 'message_id' => $result->id, - 'publish_time' => microtime(true) - $publishStart - ]; - $this->log(200, "Message has been published.", $context); - - return (int) $result->id; - } - - /** - * {@inheritDoc} - */ - public function receive(array $options = []) - { - $options = $this->mergeOptions($options); - - if (!$this->queueExists()) { - $this->create(); - } - - $messages = $this->ironmq->reserveMessages( - $this->getNameWithPrefix(), - $options['messages_to_receive'], - $options['message_timeout'], - $options['receive_wait_time'] - ); - - if (!is_array($messages)) { - $this->log(200, "No messages found in queue."); - - return []; - } - - // Convert to Message Class - foreach ($messages as &$message) { - $id = $message->id; - $body = json_decode($message->body, true); - $metadata = [ - 'reserved_count' => $message->reserved_count, - 'reservation_id' => $message->reservation_id - ]; - - unset($body['_qpush_queue']); - - $message = new Message($id, json_encode($body), $metadata); - - $this->log(200, "Message has been received.", ['message_id' => $id]); - } - - $this->reservedMessages = array_combine(array_values(array_map(function (Message $message) { - return $message->getId(); - }, $messages)), $messages); - - return $messages; - } - - /** - * {@inheritDoc} - */ - public function delete($id) - { - $reservationId = $this->getReservationId($id); - - try { - $this->ironmq->deleteMessage($this->getNameWithPrefix(), $id, $reservationId); - $this->log(200, "Message deleted.", ['message_id' => $id]); - } catch ( \Exception $e) { - if (false !== strpos($e->getMessage(), "Queue not found")) { - $this->log(400, "Queue did not exist"); - } else { - throw $e; - } - } - - return true; - } - - /** - * Checks whether or not the Queue exists - * - * This method relies on in-memory cache and the Cache provider - * to reduce the need to needlessly call the create method on an existing - * Queue. - * @return bool - * @throws \Exception - */ - public function queueExists() - { - if (isset($this->queue)) { - return true; - } - - $queueName = $this->getNameWithPrefix(); - if ($this->cache->contains($queueName)) { - $this->queue = json_decode($this->cache->fetch($queueName)); - - return true; - } - try { - $this->queue = $this->ironmq->getQueue($queueName); - $this->cache->save($queueName, json_encode($this->queue)); - } catch (\Exception $e) { - if (false !== strpos($e->getMessage(), "Queue not found")) { - $this->log(400, "Queue did not exist"); - } else { - throw $e; - } - } - - return false; - } - - /** - * Polls the Queue on Notification from IronMQ - * - * Dispatches the `{queue}.message_received` event - * - * @param NotificationEvent $event The Notification Event - * @param string $eventName Name of the event - * @param EventDispatcherInterface $dispatcher - * @return void - */ - public function onNotification(NotificationEvent $event, $eventName, EventDispatcherInterface $dispatcher) - { - $message = new Message( - $event->getNotification()->getId(), - $event->getNotification()->getBody(), - $event->getNotification()->getMetadata()->toArray() - ); - - $this->log( - 200, - "Message has been received from Push Notification.", - ['message_id' => $event->getNotification()->getId()] - ); - - $messageEvent = new MessageEvent($this->name, $message); - - $dispatcher->dispatch( - Events::Message($this->name), - $messageEvent - ); - } - - /** - * Removes the message from queue after all other listeners have fired - * - * If an earlier listener has failed or stopped propagation, this method - * will not fire and the Queued Message should become visible in queue again. - * - * Stops Event Propagation after removing the Message - * - * @param MessageEvent $event The SQS Message Event - * @return void - */ - public function onMessageReceived(MessageEvent $event) - { - $metadata = $event->getMessage()->getMetadata(); - - if (!$metadata->containsKey('iron-subscriber-message-id')) { - $id = $event->getMessage()->getId(); - $this->delete($id); - } - - $event->stopPropagation(); - } - - /** - * Get queue info - * - * This allows to get queue size. Allowing to know if processing is finished or not - * - * @return mixed - */ - public function queueInfo() - { - if ($this->queueExists()) { - $queueName = $this->getNameWithPrefix(); - $this->queue = $this->ironmq->getQueue($queueName); - - return $this->queue; - } - - return null; - } - - /** - * Publishes multiple message at once - * - * @param array $messages - * @param array $options - * - * @return array - */ - public function publishMessages(array $messages, array $options = []) - { - $options = $this->mergeOptions($options); - $publishStart = microtime(true); - - if (!$this->queueExists()) { - $this->create(); - } - - $encodedMessages = []; - foreach ($messages as $message) { - $encodedMessages[] = json_encode($message + ['_qpush_queue' => $this->name]); - } - - $result = $this->ironmq->postMessages( - $this->getNameWithPrefix(), - $encodedMessages, - [ - 'timeout' => $options['message_timeout'], - 'delay' => $options['message_delay'], - 'expires_in' => $options['message_expiration'] - ] - ); - - $context = [ - 'message_ids' => $result->ids, - 'publish_time' => microtime(true) - $publishStart - ]; - $this->log(200, "Messages have been published.", $context); - - return $result->ids; - } - - /** - * @param $id - * @return string|null - */ - private function getReservationId($id) - { - if (!array_key_exists($id, $this->reservedMessages)) { - return null; - } - - $messageToDelete = $this->reservedMessages[$id]; - if (!$messageToDelete->getMetadata()->containsKey('reservation_id')) { - return null; - } - - return $messageToDelete->getMetadata()->get('reservation_id'); - } -} diff --git a/src/Provider/ProviderInterface.php b/src/Provider/ProviderInterface.php index 873d7c0..b57acc7 100755 --- a/src/Provider/ProviderInterface.php +++ b/src/Provider/ProviderInterface.php @@ -22,9 +22,6 @@ namespace Uecode\Bundle\QPushBundle\Provider; -use Doctrine\Common\Cache\Cache; -use Monolog\Logger; - /** * @author Keith Kirk */ @@ -41,10 +38,8 @@ interface ProviderInterface * @param string $name Name of the Queue the provider is for * @param array $options An array of configuration options for the Queue * @param mixed $client A Queue Client for the provider - * @param Cache $cache An instance of Doctrine\Common\Cache\Cache - * @param Logger $logger An instance of Mongolog\Logger */ - public function __construct($name, array $options, $client, Cache $cache, Logger $logger); + public function __construct($name, array $options, $client); /** * Returns the name of the Queue that this Provider is for @@ -78,20 +73,6 @@ public function getProvider(); */ public function getOptions(); - /** - * Returns the Cache service - * - * @return Cache - */ - public function getCache(); - - /** - * Returns the Logger service - * - * @return Logger - */ - public function getLogger(); - /** * Creates the Queue * @@ -134,23 +115,9 @@ public function receive(array $options = []); public function delete($id); /** - * Destroys a Queue and clears any Queue related Cache + * Destroys a Queue * * @return bool */ public function destroy(); - - /** - * Logs data from the library - * - * This method wraps the Logger to check if logging is enabled and adds - * the Queue name and Provider automatically to the context - * - * @param int $level The log level - * @param string $message The message to log - * @param array $context The log context - * - * @return bool Whether the record was logged - */ - public function log($level, $message, array $context); } diff --git a/src/Provider/SyncProvider.php b/src/Provider/SyncProvider.php deleted file mode 100644 index 3e93084..0000000 --- a/src/Provider/SyncProvider.php +++ /dev/null @@ -1,78 +0,0 @@ -name = $name; - $this->options = $options; - $this->dispatcher = $client; - $this->cache = $cache; - $this->logger = $logger; - } - - public function getProvider() - { - return 'Sync'; - } - - public function publish(array $message, array $options = []) - { - $message = new Message(time(), $message, []); - - $this->dispatcher->dispatch( - Events::Message($this->name), - new MessageEvent($this->name, $message) - ); - - $context = ['MessageId' => $message->getId()]; - $this->log(200, 'Message received and dispatched on Sync Queue', $context); - } - - public function create() {} - - public function destroy() {} - - public function delete($id) {} - - public function receive(array $options = []) {} -} diff --git a/src/Resources/config/config.yml b/src/Resources/config/config.yml index cb923f6..6a0c1b0 100755 --- a/src/Resources/config/config.yml +++ b/src/Resources/config/config.yml @@ -1,7 +1,5 @@ #Example Configuration uecode_qpush: - cache_service: null - logging_enabled: true providers: aws: key: @@ -13,7 +11,7 @@ uecode_qpush: host: queues: default: - provider: aws #or ironmq + provider: aws options: push_notifications: true notification_retries: 3 diff --git a/src/Resources/config/parameters.yml b/src/Resources/config/parameters.yml index f1fce21..34422d6 100755 --- a/src/Resources/config/parameters.yml +++ b/src/Resources/config/parameters.yml @@ -3,8 +3,3 @@ parameters: uecode_qpush.request_listener.class: Uecode\Bundle\QPushBundle\EventListener\RequestListener uecode_qpush.registry.class: Uecode\Bundle\QPushBundle\Provider\ProviderRegistry uecode_qpush.provider.aws: Uecode\Bundle\QPushBundle\Provider\AwsProvider - uecode_qpush.provider.ironmq: Uecode\Bundle\QPushBundle\Provider\IronMqProvider - uecode_qpush.provider.sync: Uecode\Bundle\QPushBundle\Provider\SyncProvider - uecode_qpush.provider.custom: Uecode\Bundle\QPushBundle\Provider\CustomProvider - uecode_qpush.provider.file: Uecode\Bundle\QPushBundle\Provider\FileProvider - uecode_qpush.provider.doctrine: Uecode\Bundle\QPushBundle\Provider\DoctrineProvider diff --git a/src/Resources/config/services.yml b/src/Resources/config/services.yml index f2d1382..3298a97 100755 --- a/src/Resources/config/services.yml +++ b/src/Resources/config/services.yml @@ -6,12 +6,6 @@ services: alias: uecode_qpush.registry public: true - ### QPush Default File Cache - uecode_qpush.file_cache: - class: Doctrine\Common\Cache\PhpFileCache - arguments: ['%kernel.cache_dir%/qpush', qpush.php] - public: false - ### QPush Event Listeners uecode_qpush.request_listener: class: Uecode\Bundle\QPushBundle\EventListener\RequestListener diff --git a/tests/DependencyInjection/UecodeQPushExtensionTest.php b/tests/DependencyInjection/UecodeQPushExtensionTest.php index 5d4ac00..e6af8ca 100644 --- a/tests/DependencyInjection/UecodeQPushExtensionTest.php +++ b/tests/DependencyInjection/UecodeQPushExtensionTest.php @@ -66,19 +66,11 @@ public function testConfiguration() $this->assertTrue($this->container->has('uecode_qpush')); $this->assertTrue($this->container->has('uecode_qpush.test_aws')); - $this->assertTrue($this->container->has('uecode_qpush.test_file')); $this->assertTrue($this->container->has('uecode_qpush.test_aws_fifo')); $this->assertTrue($this->container->has('uecode_qpush.test_secondary_aws')); $this->assertNotSame( $this->container->get('uecode_qpush.test_aws'), $this->container->get('uecode_qpush.test_secondary_aws') ); - - $this->assertTrue($this->container->has('uecode_qpush.test_ironmq')); - $this->assertTrue($this->container->has('uecode_qpush.test_secondary_ironmq')); - $this->assertNotSame( - $this->container->get('uecode_qpush.test_ironmq'), - $this->container->get('uecode_qpush.test_secondary_ironmq') - ); } } diff --git a/tests/Event/NotificationEventTest.php b/tests/Event/NotificationEventTest.php index 320a017..a4deaf2 100644 --- a/tests/Event/NotificationEventTest.php +++ b/tests/Event/NotificationEventTest.php @@ -64,14 +64,14 @@ public function testNotificationEventConstructor() ); $this->assertInstanceOf('Uecode\Bundle\QPushBundle\Event\NotificationEvent', $event); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException('InvalidArgumentException'); $event = new NotificationEvent( 'test', 'InvalidNotificationType', new Notification(123, ['foo' => 'bar'], ['bar' => 'baz']) ); - $this->setExpectedException('PHPUnit_Framework_Error'); + $this->expectException('PHPUnit_Framework_Error'); $event = new NotificationEvent( 'test', NotificationEvent::TYPE_SUBSCRIPTION, diff --git a/tests/EventListener/RequestListenerTest.php b/tests/EventListener/RequestListenerTest.php index 5641890..752836c 100644 --- a/tests/EventListener/RequestListenerTest.php +++ b/tests/EventListener/RequestListenerTest.php @@ -26,6 +26,7 @@ use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\HttpKernel\Event\GetResponseEvent; @@ -62,48 +63,12 @@ public function setUp(): void public function testListenerDoesNothingForSubRequests() { - $event = new GetResponseEvent($this->kernel, new Request(), HttpKernelInterface::SUB_REQUEST); - $this->dispatcher->dispatch(KernelEvents::REQUEST, $event); + $event = new RequestEvent($this->kernel, new Request(), HttpKernelInterface::SUB_REQUEST); + $this->dispatcher->dispatch( $event, KernelEvents::REQUEST); $this->assertFalse($event->hasResponse()); } - public function testListenerHandlesIronMQMessageRequests() - { - $message = '{"foo": "bar","_qpush_queue":"ironmq-test"}'; - - $request = new Request([],[],[],[],[],[], $message); - $request->headers->set('iron-message-id', 123); - $request->headers->set('iron-subscriber-message-id', 456); - $request->headers->set('iron-subscriber-message-url', 'http://foo.bar'); - - $event = new GetResponseEvent($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST); - $this->dispatcher->dispatch(KernelEvents::REQUEST, $event); - - $this->assertTrue($event->hasResponse()); - $this->assertEquals("IronMQ Notification Received.", $event->getResponse()->getContent()); - } - - public function IronMqOnNotificationReceived(NotificationEvent $event) - { - $notification = $event->getNotification(); - $this->assertInstanceOf('\Uecode\Bundle\QPushBundle\Message\Notification', $notification); - - $this->assertEquals(123, $notification->getId()); - - $this->assertInternalType('array', $notification->getBody()); - $this->assertEquals($notification->getBody(), ['foo' => 'bar']); - - $this->assertInstanceOf('\Doctrine\Common\Collections\ArrayCollection', $notification->getMetadata()); - $this->assertEquals( - [ - 'iron-subscriber-message-id' => 456, - 'iron-subscriber-message-url' => 'http://foo.bar' - ], - $notification->getMetadata()->toArray() - ); - } - public function testListenerHandlesAwsNotificationRequests() { $message = [ @@ -118,9 +83,8 @@ public function testListenerHandlesAwsNotificationRequests() $request = new Request([],[],[],[],[],[], json_encode($message)); $request->headers->set('x-amz-sns-message-type', 'Notification'); - $event = new GetResponseEvent($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST); - - $this->dispatcher->dispatch(KernelEvents::REQUEST, $event); + $event = new RequestEvent($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST); + $this->dispatcher->dispatch($event, KernelEvents::REQUEST); $this->assertTrue($event->hasResponse()); $this->assertEquals("SNS Message Notification Received.", $event->getResponse()->getContent()); @@ -133,7 +97,7 @@ public function AwsOnNotificationReceived(NotificationEvent $event) $this->assertEquals(123, $notification->getId()); - $this->assertInternalType('array', $notification->getBody()); + $this->assertIsArray($notification->getBody()); $this->assertEquals($notification->getBody(), ['foo' => 'bar']); $this->assertInstanceOf('\Doctrine\Common\Collections\ArrayCollection', $notification->getMetadata()); @@ -164,8 +128,8 @@ public function testListenerHandlesAwsSubscriptionRequests() $request = new Request([],[],[],[],[],[], json_encode($message)); $request->headers->set('x-amz-sns-message-type', 'SubscriptionConfirmation'); - $event = new GetResponseEvent($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST); - $this->dispatcher->dispatch(KernelEvents::REQUEST, $event); + $event = new RequestEvent($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST); + $this->dispatcher->dispatch($event, KernelEvents::REQUEST); $this->assertTrue($event->hasResponse()); $this->assertEquals("SNS Subscription Confirmation Received.", $event->getResponse()->getContent()); diff --git a/tests/Fixtures/config_test.yml b/tests/Fixtures/config_test.yml index 6719679..c9a93cd 100644 --- a/tests/Fixtures/config_test.yml +++ b/tests/Fixtures/config_test.yml @@ -1,6 +1,4 @@ uecode_qpush: - cache_service: null - logging_enabled: true providers: aws: driver: aws @@ -12,26 +10,7 @@ uecode_qpush: key: 234 secret: 432 region: eu-west-1 - ironmq: - driver: ironmq - token: 123 - project_id: 123 - secondary_ironmq: - driver: ironmq - token: 234 - project_id: 234 - file: - driver: file - path: /tmp/my_queue queues: - test_file: - provider: file - options: - message_delay: 0 - message_timeout: 30 - message_expiration: 604800 - messages_to_receive: 1 - receive_wait_time: 3 test_aws: provider: aws options: @@ -70,35 +49,7 @@ uecode_qpush: content_based_deduplication: true subscribers: - { endpoint: http://example.com/qpush, protocol: http } - test_ironmq: - provider: ironmq - options: - push_notifications: true - notification_retries: 3 - message_delay: 0 - message_timeout: 30 - message_expiration: 604800 - messages_to_receive: 1 - receive_wait_time: 3 - subscribers: - - { endpoint: http://example.com/qpush, protocol: http } - test_secondary_ironmq: - provider: secondary_ironmq - options: - push_notifications: true - notification_retries: 3 - message_delay: 0 - message_timeout: 30 - message_expiration: 604800 - messages_to_receive: 1 - receive_wait_time: 3 - subscribers: - - { endpoint: http://example.com/qpush, protocol: http } services: event_dispatcher: - class: stdClass - logger: - class: Symfony\Bridge\Monolog\Logger - arguments: - - 'test' + class: stdClass \ No newline at end of file diff --git a/tests/MockClient/CustomMockClient.php b/tests/MockClient/CustomMockClient.php deleted file mode 100644 index c31d350..0000000 --- a/tests/MockClient/CustomMockClient.php +++ /dev/null @@ -1,72 +0,0 @@ - - */ -class CustomMockClient extends AbstractProvider -{ - /** - * Constructor for Provider classes - * - * @param string $name Name of the Queue the provider is for - * @param array $options An array of configuration options for the Queue - * @param mixed $client A Queue Client for the provider - * @param Cache $cache An instance of Doctrine\Common\Cache\Cache - * @param Logger $logger An instance of Mongolog\Logger - */ - public function __construct($name, array $options, $client, Cache $cache, Logger $logger) - { - } - - public function getProvider() - { - } - - public function create() - { - } - - public function publish(array $message, array $options = []) - { - } - - public function receive(array $options = []) - { - } - - public function delete($id) - { - } - - public function destroy() - { - } -} diff --git a/tests/MockClient/IronMqMockClient.php b/tests/MockClient/IronMqMockClient.php deleted file mode 100644 index e817bf2..0000000 --- a/tests/MockClient/IronMqMockClient.php +++ /dev/null @@ -1,111 +0,0 @@ - - */ -class IronMqMockClient -{ - private $deleteCount = 0; - - public function createQueue($queue, array $params = []) - { - $response = new \stdClass; - $response->id = '530295fe3c94fbcf0c79cffe'; - $response->name = 'test'; - $response->size = 0; - $response->total_messages = 0; - $response->project_id = '52f67d032001c00005000057'; - - return $response; - } - - public function deleteQueue($queue) - { - if ($this->deleteCount == 0) { - $this->deleteCount++; - - return true; - } - - if ($this->deleteCount == 1) { - $this->deleteCount++; - - throw new \Exception('http error: 404 | {"msg":"Queue not found"}'); - } - - throw new \Exception('Random Exception'); - } - - public function postMessage($queue, $message, $options) - { - $response = new \stdClass; - $response->id = 123; - $response->ids = [123]; - $response->msg = "Messages put on queue."; - - return $response; - } - - public function reserveMessages($queue, $count, $timeout) - { - $response = new \stdClass; - $response->id = 123; - $response->body = '{"foo":"bar","_qpush_queue":"test"}'; - $response->reservation_id = 'def456'; - $response->reserved_count = 1; - - return [$response]; - } - - public function deleteMessage($queue, $id) - { - $response = new \stdClass; - $response->id = $id; - - if ($id == 456) { - throw new \Exception('http error: 404 | {"msg":"Queue not found"}'); - } - - if ($id == 789) { - throw new \Exception('Random Exception'); - } - - return $response; - } - - public function getQueue($queue) - { - $response = new \stdClass; - $response->id = '530295fe3c94fbcf0c79cffe'; - $response->name = 'test'; - $response->size = 0; - $response->total_messages = 0; - $response->project_id = '52f67d032001c00005000057'; - - return $response; - } -} diff --git a/tests/Provider/AbstractProviderTest.php b/tests/Provider/AbstractProviderTest.php index 376b898..7143c88 100644 --- a/tests/Provider/AbstractProviderTest.php +++ b/tests/Provider/AbstractProviderTest.php @@ -57,7 +57,6 @@ private function getTestProvider(array $options = []) $options = array_merge( [ - 'logging_enabled' => false, 'push_notifications' => true, 'notification_retries' => 3, 'message_delay' => 0, @@ -75,17 +74,7 @@ private function getTestProvider(array $options = []) return new TestProvider( 'test', $options, - new \stdClass, - $this->createMock( - 'Doctrine\Common\Cache\PhpFileCache', - [], - ['/tmp', 'qpush.aws.test.php'] - ), - $this->createMock( - 'Symfony\Bridge\Monolog\Logger', - [], - ['qpush.test'] - ) + new \stdClass ); } @@ -118,29 +107,6 @@ public function testGetOptions() $this->assertTrue(is_array($options)); } - public function testGetCache() - { - $cache = $this->provider->getCache(); - - $this->assertInstanceOf('Doctrine\\Common\\Cache\\Cache', $cache); - } - - public function testGetLogger() - { - $logger = $this->provider->getLogger(); - - $this->assertInstanceOf('Monolog\\Logger', $logger); - } - - public function testLogEnabled() - { - $this->assertFalse($this->provider->log(100, 'test log', [])); - - $provider = $this->getTestProvider(['logging_enabled' => true]); - - $this->assertNull($provider->log(100, 'test log', [])); - } - public function testGetProvider() { $provider = $this->provider->getProvider(); diff --git a/tests/Provider/AwsProviderTest.php b/tests/Provider/AwsProviderTest.php index b8f8762..8a81f20 100755 --- a/tests/Provider/AwsProviderTest.php +++ b/tests/Provider/AwsProviderTest.php @@ -64,7 +64,6 @@ private function getAwsProvider(array $options = []) { $options = array_merge( [ - 'logging_enabled' => false, 'push_notifications' => true, 'notification_retries' => 3, 'message_delay' => 0, @@ -87,17 +86,7 @@ private function getAwsProvider(array $options = []) 'region' => 'us-east-1' ]); - $cache = $this->createMock( - 'Doctrine\Common\Cache\PhpFileCache', - [], - ['/tmp', 'qpush.aws.test.php'] - ); - - $logger = $this->createMock( - 'Symfony\Bridge\Monolog\Logger', [], ['qpush.test'] - ); - - return new AwsProvider('test', $options, $client, $cache, $logger); + return new AwsProvider('test', $options, $client); } public function testGetProvider() @@ -160,11 +149,6 @@ public function testCreateQueue() 'push_notifications' => false ]); - $stub = $provider->getCache(); - $stub->expects($this->once()) - ->method('contains') - ->will($this->returnValue(true)); - $this->assertTrue($provider->queueExists()); $provider->createQueue(); @@ -186,11 +170,6 @@ public function testCreateQueueFIFO() 'content_based_deduplication' => false ]); - $stub = $provider->getCache(); - $stub->expects($this->once()) - ->method('contains') - ->will($this->returnValue(true)); - $this->assertTrue($provider->queueExists()); $provider->createQueue(); @@ -232,13 +211,6 @@ public function testCreateTopic() $this->assertFalse($provider->topicExists()); - $stub = $provider->getCache(); - $stub->expects($this->once()) - ->method('contains') - ->will($this->returnValue(true)); - - $this->assertTrue($provider->topicExists()); - $provider->createTopic(); $this->assertTrue($provider->topicExists()); @@ -298,11 +270,14 @@ public function testUnsubscribeFromTopic() public function testOnNotificationSubscriptionEvent() { $dispatcher = $this->getMockForAbstractClass('Symfony\Component\EventDispatcher\EventDispatcherInterface'); - $this->provider->onNotification(new NotificationEvent( - 'test', - NotificationEvent::TYPE_SUBSCRIPTION, - new Notification(123, "test", []) - ), NotificationEvent::TYPE_SUBSCRIPTION, $dispatcher); + + $this->assertNull( + $this->provider->onNotification(new NotificationEvent( + 'test', + NotificationEvent::TYPE_SUBSCRIPTION, + new Notification(123, "test", []) + ), NotificationEvent::TYPE_SUBSCRIPTION, $dispatcher) + ); } @@ -314,18 +289,22 @@ public function testOnNotificationMessageEvent() new Notification(123, "test", []) ); - $this->provider->onNotification( - $event, - NotificationEvent::TYPE_MESSAGE, - $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface') + $this->assertNull( + $this->provider->onNotification( + $event, + NotificationEvent::TYPE_MESSAGE, + $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface') + ) ); } public function testOnMessageReceived() { - $this->provider->onMessageReceived(new MessageEvent( - 'test', - new Message(123, ['foo' => 'bar'], []) - )); + $this->assertNull( + $this->provider->onMessageReceived(new MessageEvent( + 'test', + new Message(123, ['foo' => 'bar'], []) + )) + ); } } diff --git a/tests/Provider/CustomProviderTest.php b/tests/Provider/CustomProviderTest.php deleted file mode 100644 index 93207b5..0000000 --- a/tests/Provider/CustomProviderTest.php +++ /dev/null @@ -1,107 +0,0 @@ -provider = $this->getCustomProvider(); - } - - public function testGetProvider() - { - $provider = $this->provider->getProvider(); - - $this->assertEquals('Custom', $provider); - } - - public function testPublish() - { - $this->setNoOpExpectation(); - - $this->provider->publish(['foo' => 'bar']); - } - - public function testCreate() - { - $this->setNoOpExpectation(); - - $this->provider->create(); - } - - public function testDestroy() - { - $this->setNoOpExpectation(); - - $this->provider->destroy(); - } - - public function testDelete() - { - $this->setNoOpExpectation(); - - $this->provider->delete('foo'); - } - - public function testReceive() - { - $this->setNoOpExpectation(); - - $this->provider->receive(); - } - - - protected function getCustomProvider() - { - $options = [ - 'logging_enabled' => false, - 'push_notifications' => true, - 'notification_retries' => 3, - 'message_delay' => 0, - 'message_timeout' => 30, - 'message_expiration' => 604800, - 'messages_to_receive' => 1, - 'receive_wait_time' => 3, - 'subscribers' => [] - ]; - - $cache = $this->createMock( - 'Doctrine\Common\Cache\PhpFileCache', - [], - ['/tmp', 'qpush.custom.test.php'] - ); - - $this->logger = $this->createMock( - 'Monolog\Logger', [], ['qpush.test'] - ); - - $this->mock = new CustomMockClient('custom', $options, null, $cache, $this->logger); - - return new CustomProvider('test', $options, $this->mock, $cache, $this->logger); - } - - protected function setNoOpExpectation() - { - $this->logger - ->expects($this->never()) - ->method(new \PHPUnit_Framework_Constraint_IsAnything()); - } -} diff --git a/tests/Provider/FileProviderTest.php b/tests/Provider/FileProviderTest.php deleted file mode 100644 index e890744..0000000 --- a/tests/Provider/FileProviderTest.php +++ /dev/null @@ -1,214 +0,0 @@ - - */ -class FileProviderTest extends TestCase -{ - /** @var FileProvider */ - protected $provider; - protected $basePath; - protected $queueHash; - protected $umask; - - public function setUp(): void - { - $this->umask = umask(0); - $this->basePath = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.time().rand(0, 1000); - mkdir($this->basePath); - $this->provider = $this->getFileProvider(); - } - - public function tearDown(): void - { - $this->clean($this->basePath); - umask($this->umask); - } - - /** - * @param string $file - */ - protected function clean($file) - { - if (is_dir($file) && !is_link($file)) { - $dir = new \FilesystemIterator($file); - foreach ($dir as $childFile) { - $this->clean($childFile); - } - - rmdir($file); - } else if (is_file($file)) { - unlink($file); - } - } - - private function getFileProvider(array $options = []) - { - $options = array_merge( - [ - 'path' => $this->basePath, - 'logging_enabled' => false, - 'message_delay' => 0, - 'message_timeout' => 30, - 'message_expiration' => 604800, - 'messages_to_receive' => 1, - ], - $options - ); - - $cache = $this->createMock( - 'Doctrine\Common\Cache\PhpFileCache', - [], - ['/tmp', 'qpush.aws.test.php'] - ); - - $logger = $this->createMock( - 'Symfony\Bridge\Monolog\Logger', [], ['qpush.test'] - ); - - $this->queueHash = str_replace('-', '', md5('test')); - - return new FileProvider('test', $options, null, $cache, $logger); - } - - public function testGetProvider() - { - $provider = $this->provider->getProvider(); - - $this->assertEquals('File', $provider); - } - - public function testCreate() - { - $this->assertTrue($this->provider->create()); - $this->assertTrue(is_readable($this->basePath.DIRECTORY_SEPARATOR.$this->queueHash)); - $this->assertTrue(is_writable($this->basePath.DIRECTORY_SEPARATOR.$this->queueHash)); - } - - public function testDestroy() - { - $this->provider->destroy(); - $this->assertFalse(is_dir($this->basePath.DIRECTORY_SEPARATOR.$this->queueHash)); - } - - public function testReceive() - { - $this->provider->create(); - $this->assertTrue(is_array($this->provider->receive())); - } - - public function testDelete() - { - $this->provider->create(); - - $path = substr(hash('md5', '123'), 0, 3); - mkdir($this->basePath.DIRECTORY_SEPARATOR.$this->queueHash.DIRECTORY_SEPARATOR.$path); - touch($this->basePath.DIRECTORY_SEPARATOR.$this->queueHash.DIRECTORY_SEPARATOR.$path.DIRECTORY_SEPARATOR.'123.json'); - - $messages = $this->provider->receive(); - $this->assertNotEmpty($messages); - $this->assertTrue($this->provider->delete(123)); - } - - public function testPublish() - { - $this->provider->create(); - $content = [ - ['testing'], - ['testing 123'] - ]; - $this->provider->publish($content[0]); - $this->provider->publish($content[1]); - $messagesA = $this->provider->receive(); - $this->assertEquals(1, count($messagesA)); - $this->assertContains($messagesA[0]->getBody(), $content); - $messagesB = $this->provider->receive(); - $this->assertEquals(1, count($messagesB)); - $this->assertContains($messagesB[0]->getBody(), $content); - $this->assertNotEquals($messagesA[0]->getBody(), $messagesB[0]->getBody()); - } - - public function testPublishDelay() { - $this->provider->create(); - $provider = $this->getFileProvider([ - 'message_delay' => 2, - ]); - $provider->publish(['testing']); - $messages = $provider->receive(); - $this->assertEmpty($messages); - } - - public function testOnMessageReceived() - { - $this->provider->create(); - $id = $this->provider->publish(['foo' => 'bar']); - $path = substr(hash('md5', $id), 0, 3); - $this->assertTrue(is_file($this->basePath.DIRECTORY_SEPARATOR.$this->queueHash.DIRECTORY_SEPARATOR.$path.DIRECTORY_SEPARATOR.$id.'.json')); - $this->provider->onMessageReceived(new MessageEvent( - 'test', - $this->provider->receive()[0] - )); - $this->assertFalse(is_file($this->basePath.DIRECTORY_SEPARATOR.$this->queueHash.DIRECTORY_SEPARATOR.$path.DIRECTORY_SEPARATOR.$id.'.json')); - } - - public function testCleanUp() - { - $this->provider->create(); - $provider = $this->getFileProvider([ - 'message_expiration' => 10, - ]); - - $id = $provider->publish(['testing']); - $this->mockMessageAge($id, 3600); - $id = $provider->publish(['testing 123']); - $this->mockMessageAge($id, 3600); - - $provider->cleanUp(); - - $finder = new Finder(); - $files = $finder->files()->in($this->basePath . DIRECTORY_SEPARATOR . $this->queueHash); - $this->assertCount(0, $files); - } - - /** - * @see https://github.com/uecode/qpush-bundle/issues/93 - */ - public function testCleanUpDoesNotRemoveCurrentMessages() { - $this->provider->create(); - $provider = $this->getFileProvider([ - 'message_expiration' => 10, - ]); - $currentMessage = ['dont remove me']; - - $id = $provider->publish(['testing']); - $this->mockMessageAge($id, 3600); - $id = $provider->publish(['testing 123']); - $this->mockMessageAge($id, 3600); - $provider->publish($currentMessage); - - $provider->cleanUp(); - $messages = $provider->receive(); - $this->assertCount(1, $messages); - $this->assertSame($currentMessage, $messages[0]->getBody()); - } - - /** - * @param string $id - * @param int $ageInSeconds - * @return string - */ - protected function mockMessageAge($id, $ageInSeconds) { - $path = substr(hash('md5', $id), 0, 3); - touch( - $this->basePath.DIRECTORY_SEPARATOR.$this->queueHash.DIRECTORY_SEPARATOR.$path.DIRECTORY_SEPARATOR.$id.'.json', - time() - $ageInSeconds - ); - } -} \ No newline at end of file diff --git a/tests/Provider/IronMqProviderTest.php b/tests/Provider/IronMqProviderTest.php deleted file mode 100755 index b682ca5..0000000 --- a/tests/Provider/IronMqProviderTest.php +++ /dev/null @@ -1,207 +0,0 @@ - - */ -class IronMqProviderTest extends TestCase -{ - /** - * Mock Client - * - * @var \stdClass - */ - protected $provider; - - public function setUp(): void - { - $this->provider = $this->getIronMqProvider(); - } - - public function tearDown(): void - { - $this->provider = null; - } - - private function getIronMqProvider(array $options = []) - { - $options = array_merge( - [ - 'logging_enabled' => false, - 'push_notifications' => true, - 'push_type' => 'multicast', - 'notification_retries' => 3, - 'notification_retries_delay' => 60, - 'message_delay' => 0, - 'message_timeout' => 30, - 'message_expiration' => 604800, - 'messages_to_receive' => 1, - 'rate_limit' => -1, - 'receive_wait_time' => 3, - 'subscribers' => [ - [ 'protocol' => 'http', 'endpoint' => 'http://fake.com' ] - ] - ], - $options - ); - - $client = new IronMqMockClient([ - 'token' => '123_this_is_a_token', - 'project_id' => '123_this_is_a_project_id', - ]); - - return new IronMqProvider( - 'test', - $options, - $client, - $this->createMock( - 'Doctrine\Common\Cache\PhpFileCache', - [], - ['/tmp', 'qpush.ironmq.test.php'] - ), - $this->createMock( - 'Symfony\Bridge\Monolog\Logger', - [], - ['qpush.test'] - ) - ); - } - - public function testGetProvider() - { - $provider = $this->provider->getProvider(); - - $this->assertEquals('IronMQ', $provider); - } - - public function testCreate() - { - $this->assertFalse($this->provider->queueExists()); - - $this->assertTrue($this->provider->queueExists()); - - $this->assertTrue($this->provider->create()); - $this->assertTrue($this->provider->queueExists()); - - $provider = $this->getIronMqProvider([ - 'subscribers' => [ - [ 'protocol' => 'email', 'endpoint' => 'test@foo.com' ] - ] - ]); - - $this->setExpectedException('InvalidArgumentException'); - $provider->create(); - } - - public function testDestroy() - { - // First call returns true when the queue exists - $this->assertTrue($this->provider->destroy()); - - // Second call catches exception and returns true when the queue - // does not exists - $this->assertTrue($this->provider->destroy()); - - // Last call throws an exception if there is an exception outside - // of a HTTP 404 - $this->setExpectedException('Exception'); - $this->provider->destroy(); - } - - public function testPublish() - { - $provider = $this->getIronMqProvider([ - 'push_notifications' => false - ]); - - $this->assertEquals(123, $provider->publish(['foo' => 'bar'])); - } - - public function testReceive() - { - $messages = $this->provider->receive(); - $this->assertInternalType('array', $messages); - $this->assertEquals(['foo' => 'bar'], $messages[0]->getBody()); - } - - public function testDelete() - { - // First call returns true when the queue exists - $this->assertTrue($this->provider->delete(123)); - - // Second call catches exception and returns true when the queue - // does not exists - $this->assertTrue($this->provider->delete(456)); - - // Last call throws an exception if there is an exception outside - // of a HTTP 404 - $this->setExpectedException('Exception'); - $this->provider->delete(789); - } - - public function testOnNotification() - { - $event = new NotificationEvent( - 'test', - NotificationEvent::TYPE_MESSAGE, - new Notification(123, "test", []) - ); - - $this->provider->onNotification( - $event, - NotificationEvent::TYPE_MESSAGE, - $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface') - ); - } - - public function testOnMessageReceived() - { - $this->provider->onMessageReceived(new MessageEvent( - 'test', - new Message(123, ['foo' => 'bar'], []) - )); - } - - public function testQueueInfo() - { - $this->assertNull($this->provider->queueInfo()); - - $this->provider->create(); - $queue = $this->provider->queueInfo(); - $this->assertEquals('530295fe3c94fbcf0c79cffe', $queue->id); - $this->assertEquals('test', $queue->name); - $this->assertEquals('52f67d032001c00005000057', $queue->project_id); - } -} diff --git a/tests/Provider/ProviderRegisteryTest.php b/tests/Provider/ProviderRegisteryTest.php index 487d985..4b210c0 100644 --- a/tests/Provider/ProviderRegisteryTest.php +++ b/tests/Provider/ProviderRegisteryTest.php @@ -43,7 +43,7 @@ public function testRegistry() $this->assertEquals($this->createMock($interface), $registry->get('test')); - $this->setExpectedException('InvalidArgumentException'); + $this->expectException('InvalidArgumentException'); $registry->get('foo'); } } diff --git a/tests/Provider/SyncProviderTest.php b/tests/Provider/SyncProviderTest.php deleted file mode 100644 index ca3c626..0000000 --- a/tests/Provider/SyncProviderTest.php +++ /dev/null @@ -1,124 +0,0 @@ -dispatcher = $this->createMock( - 'Symfony\Component\EventDispatcher\EventDispatcherInterface' - ); - - $this->provider = $this->getSyncProvider(); - } - - public function testGetProvider() - { - $provider = $this->provider->getProvider(); - - $this->assertEquals('Sync', $provider); - } - - public function testPublish() - { - $this->dispatcher - ->expects($this->once()) - ->method('dispatch') - ->with( - Events::Message($this->provider->getName()), - new \PHPUnit_Framework_Constraint_IsInstanceOf('Uecode\Bundle\QPushBundle\Event\MessageEvent') - ); - - $this->provider->publish(['foo' => 'bar']); - } - - public function testCreate() - { - $this->setNoOpExpectation(); - - $this->provider->create(); - } - - public function testDestroy() - { - $this->setNoOpExpectation(); - - $this->provider->destroy(); - } - - public function testDelete() - { - $this->setNoOpExpectation(); - - $this->provider->delete('foo'); - } - - public function testReceive() - { - $this->setNoOpExpectation(); - - $this->provider->receive(); - } - - - protected function getSyncProvider() - { - $options = [ - 'logging_enabled' => false, - 'push_notifications' => true, - 'notification_retries' => 3, - 'message_delay' => 0, - 'message_timeout' => 30, - 'message_expiration' => 604800, - 'messages_to_receive' => 1, - 'receive_wait_time' => 3, - 'subscribers' => [ - [ 'protocol' => 'http', 'endpoint' => 'http://fake.com' ] - ] - ]; - - $cache = $this->createMock( - 'Doctrine\Common\Cache\PhpFileCache', - [], - ['/tmp', 'qpush.aws.test.php'] - ); - - $this->logger = $this->createMock( - 'Monolog\Logger', [], ['qpush.test'] - ); - - return new SyncProvider('test', $options, $this->dispatcher, $cache, $this->logger); - } - - protected function setNoOpExpectation() - { - $this->dispatcher - ->expects($this->never()) - ->method(new \PHPUnit_Framework_Constraint_IsAnything()); - - $this->logger - ->expects($this->never()) - ->method(new \PHPUnit_Framework_Constraint_IsAnything()); - } -} diff --git a/tests/Provider/TestProvider.php b/tests/Provider/TestProvider.php index 6282e67..326ec5d 100755 --- a/tests/Provider/TestProvider.php +++ b/tests/Provider/TestProvider.php @@ -40,13 +40,11 @@ class TestProvider extends AbstractProvider */ protected $client; - public function __construct($name, array $options, $client, Cache $cache, Logger $logger) + public function __construct($name, array $options, $client) { $this->name = $name; $this->options = $options; $this->client = $client; - $this->cache = $cache; - $this->logger = $logger; } public function getProvider() From b85f206860acfa1c33f44179031dd654860ff147 Mon Sep 17 00:00:00 2001 From: Manuel Reinhard Date: Tue, 12 Oct 2021 15:43:35 +0200 Subject: [PATCH 04/16] Require AWS SDK 3.x --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 23c94c8..647358d 100755 --- a/composer.json +++ b/composer.json @@ -11,7 +11,7 @@ "symfony/config": "^4.0", "symfony/http-kernel": "^4.0", "symfony/console": "^4.0", - "aws/aws-sdk-php": "~2.5", + "aws/aws-sdk-php": "~3.0", "doctrine/collections": "^1.6" }, "require-dev": { From da298086d065a9c9875c9f3454e7d611f8abb8be Mon Sep 17 00:00:00 2001 From: Manuel Reinhard Date: Mon, 25 Oct 2021 16:47:06 +0200 Subject: [PATCH 05/16] Set created service to be synthetic meanung created at runtime --- src/DependencyInjection/UecodeQPushExtension.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/DependencyInjection/UecodeQPushExtension.php b/src/DependencyInjection/UecodeQPushExtension.php index ac68106..e93473b 100755 --- a/src/DependencyInjection/UecodeQPushExtension.php +++ b/src/DependencyInjection/UecodeQPushExtension.php @@ -81,6 +81,7 @@ public function load(array $configs, ContainerBuilder $container) ); $definition->setPublic(true); + $definition->setSynthetic(true); $isProviderAWS = $config['providers'][$provider]['driver'] === 'aws'; $isQueueNameSet = isset($values['options']['queue_name']) && !empty($values['options']['queue_name']); From 8931c2ededba7279d7d28ba4d4d8c05dbe5e6227 Mon Sep 17 00:00:00 2001 From: Manuel Reinhard Date: Fri, 17 Dec 2021 15:00:35 +0100 Subject: [PATCH 06/16] Undo making services synthetic --- src/DependencyInjection/UecodeQPushExtension.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/DependencyInjection/UecodeQPushExtension.php b/src/DependencyInjection/UecodeQPushExtension.php index e93473b..ac68106 100755 --- a/src/DependencyInjection/UecodeQPushExtension.php +++ b/src/DependencyInjection/UecodeQPushExtension.php @@ -81,7 +81,6 @@ public function load(array $configs, ContainerBuilder $container) ); $definition->setPublic(true); - $definition->setSynthetic(true); $isProviderAWS = $config['providers'][$provider]['driver'] === 'aws'; $isQueueNameSet = isset($values['options']['queue_name']) && !empty($values['options']['queue_name']); From 1f4313d5da8a8d83cbee4584faaabcfbf9f75288 Mon Sep 17 00:00:00 2001 From: Manuel Reinhard Date: Mon, 20 Dec 2021 11:04:12 +0100 Subject: [PATCH 07/16] Re-add SyncProvider --- .../UecodeQPushExtension.php | 57 ++------------- src/Provider/SyncProvider.php | 70 +++++++++++++++++++ src/Resources/config/parameters.yml | 1 + 3 files changed, 75 insertions(+), 53 deletions(-) create mode 100644 src/Provider/SyncProvider.php diff --git a/src/DependencyInjection/UecodeQPushExtension.php b/src/DependencyInjection/UecodeQPushExtension.php index ac68106..203a150 100755 --- a/src/DependencyInjection/UecodeQPushExtension.php +++ b/src/DependencyInjection/UecodeQPushExtension.php @@ -74,6 +74,10 @@ public function load(array $configs, ContainerBuilder $container) $provider ); break; + case 'sync': + $class = $container->getParameter('uecode_qpush.provider.sync'); + $client = $this->createSyncClient(); + break; } $definition = new Definition( @@ -169,44 +173,6 @@ private function createAwsClient($config, ContainerBuilder $container, $name) return new Reference($service); } - /** - * Creates a definition for the IronMQ provider - * - * @param array $config A Configuration array for the provider - * @param ContainerBuilder $container The container - * @param string $name The provider key - * - * @throws RuntimeException - * - * @return Reference - */ - private function createIronMQClient($config, ContainerBuilder $container, $name) - { - $service = sprintf('uecode_qpush.provider.%s', $name); - - if (!$container->hasDefinition($service)) { - - if (!class_exists('IronMQ\IronMQ')) { - throw new RuntimeException('You must require "iron-io/iron_mq" to use the Iron MQ provider.'); - } - - $ironmq = new Definition('IronMQ\IronMQ'); - $ironmq->setArguments([ - [ - 'token' => $config['token'], - 'project_id' => $config['project_id'], - 'host' => sprintf('%s.iron.io', $config['host']), - 'port' => $config['port'], - 'api_version' => $config['api_version'] - ] - ]); - - $container->setDefinition($service, $ironmq)->setPublic(false); - } - - return new Reference($service); - } - /** * @return Reference */ @@ -215,21 +181,6 @@ private function createSyncClient() return new Reference('event_dispatcher'); } - private function createDoctrineClient($config) - { - return new Reference($config['entity_manager']); - } - - /** - * @param string $serviceId - * - * @return Reference - */ - private function createCustomClient($serviceId) - { - return new Reference($serviceId); - } - /** * Returns the Extension Alias * diff --git a/src/Provider/SyncProvider.php b/src/Provider/SyncProvider.php new file mode 100644 index 0000000..e42b718 --- /dev/null +++ b/src/Provider/SyncProvider.php @@ -0,0 +1,70 @@ +name = $name; + $this->options = $options; + $this->dispatcher = $client; + } + + public function getProvider() + { + return 'Sync'; + } + + public function publish(array $message, array $options = []) + { + $message = new Message(time(), $message, []); + + $this->dispatcher->dispatch( + Events::Message($this->name), + new MessageEvent($this->name, $message) + ); + } + + public function create() {} + + public function destroy() {} + + public function delete($id) {} + + public function receive(array $options = []) {} +} \ No newline at end of file diff --git a/src/Resources/config/parameters.yml b/src/Resources/config/parameters.yml index 34422d6..34f68ab 100755 --- a/src/Resources/config/parameters.yml +++ b/src/Resources/config/parameters.yml @@ -3,3 +3,4 @@ parameters: uecode_qpush.request_listener.class: Uecode\Bundle\QPushBundle\EventListener\RequestListener uecode_qpush.registry.class: Uecode\Bundle\QPushBundle\Provider\ProviderRegistry uecode_qpush.provider.aws: Uecode\Bundle\QPushBundle\Provider\AwsProvider + uecode_qpush.provider.sync: Uecode\Bundle\QPushBundle\Provider\SyncProvider \ No newline at end of file From 1fff34994083855d73f8d8f4813cf1a804e17d58 Mon Sep 17 00:00:00 2001 From: Manuel Reinhard Date: Mon, 20 Dec 2021 11:10:23 +0100 Subject: [PATCH 08/16] Fix tests --- tests/MockClient/AwsMockClient.php | 2 +- tests/Provider/SyncProviderTest.php | 108 ++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 tests/Provider/SyncProviderTest.php diff --git a/tests/MockClient/AwsMockClient.php b/tests/MockClient/AwsMockClient.php index fbede38..e58c504 100644 --- a/tests/MockClient/AwsMockClient.php +++ b/tests/MockClient/AwsMockClient.php @@ -27,7 +27,7 @@ * * @author Keith Kirk */ -class AwsMockClient extends \Aws\Common\Aws +class AwsMockClient { public function get($name, $throwAway = false) { diff --git a/tests/Provider/SyncProviderTest.php b/tests/Provider/SyncProviderTest.php new file mode 100644 index 0000000..0aec12c --- /dev/null +++ b/tests/Provider/SyncProviderTest.php @@ -0,0 +1,108 @@ +dispatcher = $this->createMock( + 'Symfony\Component\EventDispatcher\EventDispatcherInterface' + ); + + $this->provider = $this->getSyncProvider(); + } + + public function testGetProvider() + { + $provider = $this->provider->getProvider(); + + $this->assertEquals('Sync', $provider); + } + + public function testPublish() + { + $this->dispatcher + ->expects($this->once()) + ->method('dispatch') + ->with( + Events::Message($this->provider->getName()), + new IsInstanceOf('Uecode\Bundle\QPushBundle\Event\MessageEvent') + ); + + $this->provider->publish(['foo' => 'bar']); + } + + public function testCreate() + { + $this->setNoOpExpectation(); + + $this->provider->create(); + } + + public function testDestroy() + { + $this->setNoOpExpectation(); + + $this->provider->destroy(); + } + + public function testDelete() + { + $this->setNoOpExpectation(); + + $this->provider->delete('foo'); + } + + public function testReceive() + { + $this->setNoOpExpectation(); + + $this->provider->receive(); + } + + + protected function getSyncProvider() + { + $options = [ + 'logging_enabled' => false, + 'push_notifications' => true, + 'notification_retries' => 3, + 'message_delay' => 0, + 'message_timeout' => 30, + 'message_expiration' => 604800, + 'messages_to_receive' => 1, + 'receive_wait_time' => 3, + 'subscribers' => [ + [ 'protocol' => 'http', 'endpoint' => 'http://fake.com' ] + ] + ]; + + return new SyncProvider('test', $options, $this->dispatcher); + } + + protected function setNoOpExpectation() + { + $this->dispatcher + ->expects($this->never()) + ->method(new IsAnything()); + } +} \ No newline at end of file From 4662b5ed29b7220b8231f44c52c5921df246c3fa Mon Sep 17 00:00:00 2001 From: Manuel Reinhard Date: Fri, 24 Dec 2021 16:08:03 +0100 Subject: [PATCH 09/16] Re-add $this->topicExists call --- src/Provider/AwsProvider.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Provider/AwsProvider.php b/src/Provider/AwsProvider.php index c116a4b..f42632a 100755 --- a/src/Provider/AwsProvider.php +++ b/src/Provider/AwsProvider.php @@ -186,6 +186,11 @@ public function publish(array $message, array $options = []) } if ($options['push_notifications']) { + + if (!$this->topicExists()) { + $this->create(); + } + $message = [ 'default' => $this->getNameWithPrefix(), 'sqs' => json_encode($message), From ea87c753d9e84e8b623c7cfed3948ab18820c8c0 Mon Sep 17 00:00:00 2001 From: Manuel Reinhard Date: Fri, 24 Dec 2021 21:03:50 +0100 Subject: [PATCH 10/16] Re-add definition tags --- .../UecodeQPushExtension.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/DependencyInjection/UecodeQPushExtension.php b/src/DependencyInjection/UecodeQPushExtension.php index 203a150..cab5f55 100755 --- a/src/DependencyInjection/UecodeQPushExtension.php +++ b/src/DependencyInjection/UecodeQPushExtension.php @@ -85,6 +85,23 @@ public function load(array $configs, ContainerBuilder $container) ); $definition->setPublic(true); + $definition + ->addTag( + 'uecode_qpush.event_listener', + [ + 'event' => "{$queue}.on_notification", + 'method' => "onNotification", + 'priority' => 255 + ] + ) + ->addTag( + 'uecode_qpush.event_listener', + [ + 'event' => "{$queue}.message_received", + 'method' => "onMessageReceived", + 'priority' => -255 + ] + ); $isProviderAWS = $config['providers'][$provider]['driver'] === 'aws'; $isQueueNameSet = isset($values['options']['queue_name']) && !empty($values['options']['queue_name']); From 597ade1297fa45c5e1d633f076ff05393729b590 Mon Sep 17 00:00:00 2001 From: Pawel Skotnicki Date: Fri, 20 Jan 2023 12:55:34 +0100 Subject: [PATCH 11/16] Apply rector rules for Symfony 4.0-4.4 --- src/Command/QueueBuildCommand.php | 4 +- src/Command/QueueDestroyCommand.php | 4 +- src/Command/QueuePublishCommand.php | 4 +- src/Command/QueueReceiveCommand.php | 4 +- src/Event/MessageEvent.php | 2 +- src/Event/NotificationEvent.php | 2 +- src/EventListener/RequestListener.php | 51 ++++++++++--------- src/Provider/SyncProvider.php | 4 +- .../UecodeQPushExtensionTest.php | 2 +- 9 files changed, 39 insertions(+), 38 deletions(-) diff --git a/src/Command/QueueBuildCommand.php b/src/Command/QueueBuildCommand.php index 3e6f94c..3e02a76 100755 --- a/src/Command/QueueBuildCommand.php +++ b/src/Command/QueueBuildCommand.php @@ -69,7 +69,7 @@ protected function configure() ; } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $this->output = $output; $registry = $this->container->get('uecode_qpush'); @@ -77,7 +77,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $name = $input->getArgument('name'); if (null !== $name) { - return $this->buildQueue($registry, $name); + return (int) $this->buildQueue($registry, $name); } foreach ($registry->all() as $queue) { diff --git a/src/Command/QueueDestroyCommand.php b/src/Command/QueueDestroyCommand.php index 763e6c4..9c1b6da 100755 --- a/src/Command/QueueDestroyCommand.php +++ b/src/Command/QueueDestroyCommand.php @@ -77,7 +77,7 @@ protected function configure() ; } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $this->output = $output; $registry = $this->container->get('uecode_qpush'); @@ -97,7 +97,7 @@ protected function execute(InputInterface $input, OutputInterface $output) } } - return $this->destroyQueue($registry, $name); + return (int) $this->destroyQueue($registry, $name); } if (!$input->getOption('force')) { diff --git a/src/Command/QueuePublishCommand.php b/src/Command/QueuePublishCommand.php index 9088eff..b03852e 100755 --- a/src/Command/QueuePublishCommand.php +++ b/src/Command/QueuePublishCommand.php @@ -73,7 +73,7 @@ protected function configure() ; } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $this->output = $output; $registry = $this->container->get('uecode_qpush'); @@ -81,7 +81,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $name = $input->getArgument('name'); $message = $input->getArgument('message'); - return $this->sendMessage($registry, $name, $message); + return (int) $this->sendMessage($registry, $name, $message); } private function sendMessage($registry, $name, $message) diff --git a/src/Command/QueueReceiveCommand.php b/src/Command/QueueReceiveCommand.php index 7e89ba3..e4e6db9 100755 --- a/src/Command/QueueReceiveCommand.php +++ b/src/Command/QueueReceiveCommand.php @@ -71,7 +71,7 @@ protected function configure() ; } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $this->output = $output; $registry = $this->container->get('uecode_qpush'); @@ -79,7 +79,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $name = $input->getArgument('name'); if (null !== $name) { - return $this->pollQueue($registry, $name); + return (int) $this->pollQueue($registry, $name); } foreach ($registry->all() as $queue) { diff --git a/src/Event/MessageEvent.php b/src/Event/MessageEvent.php index 4434e4f..b633efa 100755 --- a/src/Event/MessageEvent.php +++ b/src/Event/MessageEvent.php @@ -28,7 +28,7 @@ /** * @author Keith Kirk */ -class MessageEvent extends Event +class MessageEvent extends \Symfony\Contracts\EventDispatcher\Event { /** * Queue name diff --git a/src/Event/NotificationEvent.php b/src/Event/NotificationEvent.php index 0db73db..e67f021 100755 --- a/src/Event/NotificationEvent.php +++ b/src/Event/NotificationEvent.php @@ -28,7 +28,7 @@ /** * @author Keith Kirk */ -class NotificationEvent extends Event +class NotificationEvent extends \Symfony\Contracts\EventDispatcher\Event { /** * A Subscription Notification Type diff --git a/src/EventListener/RequestListener.php b/src/EventListener/RequestListener.php index c170090..8a99780 100644 --- a/src/EventListener/RequestListener.php +++ b/src/EventListener/RequestListener.php @@ -25,6 +25,7 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\HttpKernel; use Uecode\Bundle\QPushBundle\Event\Events; use Uecode\Bundle\QPushBundle\Event\NotificationEvent; @@ -52,11 +53,11 @@ public function __construct(EventDispatcherInterface $dispatcher) { } /** - * Kernel Request Event Handler for QPush Notifications - * - * @param GetResponseEvent $event The Kernel Request's GetResponseEvent - */ - public function onKernelRequest(GetResponseEvent $event) { + * Kernel Request Event Handler for QPush Notifications + * + * @param RequestEvent $event The Kernel Request's GetResponseEvent + */ + public function onKernelRequest(RequestEvent $event) { if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) { return; } @@ -73,12 +74,12 @@ public function onKernelRequest(GetResponseEvent $event) { } /** - * Handles Messages sent from a IronMQ Push Queue - * - * @param GetResponseEvent $event The Kernel Request's GetResponseEvent - * @return string|void - */ - private function handleIronMqNotifications(GetResponseEvent $event) { + * Handles Messages sent from a IronMQ Push Queue + * + * @param RequestEvent $event The Kernel Request's GetResponseEvent + * @return string|void + */ + private function handleIronMqNotifications(RequestEvent $event) { $headers = $event->getRequest()->headers; $messageId = $headers->get('iron-message-id'); @@ -109,12 +110,12 @@ private function handleIronMqNotifications(GetResponseEvent $event) { } /** - * Handles Notifications sent from AWS SNS - * - * @param GetResponseEvent $event The Kernel Request's GetResponseEvent - * @return string - */ - private function handleSnsNotifications(GetResponseEvent $event) { + * Handles Notifications sent from AWS SNS + * + * @param RequestEvent $event The Kernel Request's GetResponseEvent + * @return string + */ + private function handleSnsNotifications(RequestEvent $event) { $notification = json_decode((string) $event->getRequest()->getContent(), true); $type = $event->getRequest()->headers->get('x-amz-sns-message-type'); @@ -169,14 +170,14 @@ private function handleSnsNotifications(GetResponseEvent $event) { } /** - * Get the name of the IronMq queue. - * - * @param GetResponseEvent $event - * @param array $message - * - * @return string - */ - private function getIronMqQueueName(GetResponseEvent $event, array&$message) { + * Get the name of the IronMq queue. + * + * @param RequestEvent $event + * @param array $message + * + * @return string + */ + private function getIronMqQueueName(RequestEvent $event, array&$message) { if (array_key_exists('_qpush_queue', $message)) { return $message['_qpush_queue']; } else if (null !== ($subscriberUrl = $event->getRequest()->headers->get('iron-subscriber-message-url'))) { diff --git a/src/Provider/SyncProvider.php b/src/Provider/SyncProvider.php index e42b718..5ed37c4 100644 --- a/src/Provider/SyncProvider.php +++ b/src/Provider/SyncProvider.php @@ -55,8 +55,8 @@ public function publish(array $message, array $options = []) $message = new Message(time(), $message, []); $this->dispatcher->dispatch( - Events::Message($this->name), - new MessageEvent($this->name, $message) + new MessageEvent($this->name, $message), + Events::Message($this->name) ); } diff --git a/tests/DependencyInjection/UecodeQPushExtensionTest.php b/tests/DependencyInjection/UecodeQPushExtensionTest.php index e6af8ca..21c9614 100644 --- a/tests/DependencyInjection/UecodeQPushExtensionTest.php +++ b/tests/DependencyInjection/UecodeQPushExtensionTest.php @@ -61,7 +61,7 @@ public function testConfiguration() $loader = new YamlFileLoader($this->container, new FileLocator(__DIR__.'/../Fixtures/')); $loader->load('config_test.yml'); - $this->container->compile(); + $this->container->compile(true); $this->assertTrue($this->container->has('uecode_qpush')); From 15d066084cb256a95076ec98e65170c3e0fa9e44 Mon Sep 17 00:00:00 2001 From: Pawel Skotnicki Date: Fri, 20 Jan 2023 13:11:31 +0100 Subject: [PATCH 12/16] Allow Symfony 5 components in composer.json --- composer.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/composer.json b/composer.json index 647358d..41a3e98 100755 --- a/composer.json +++ b/composer.json @@ -7,16 +7,16 @@ "license": "Apache-2.0", "require": { "php": ">=7.3", - "symfony/dependency-injection": "^4.0", - "symfony/config": "^4.0", - "symfony/http-kernel": "^4.0", - "symfony/console": "^4.0", + "symfony/dependency-injection": "^4.0|^5.0", + "symfony/config": "^4.0|^5.0", + "symfony/http-kernel": "^4.0|^5.0", + "symfony/console": "^4.0|^5.0", "aws/aws-sdk-php": "~3.0", "doctrine/collections": "^1.6" }, "require-dev": { - "symfony/phpunit-bridge": "^4.0", - "symfony/yaml": "^4.0" + "symfony/phpunit-bridge": "^4.0|^5.0", + "symfony/yaml": "^4.0|^5.0" }, "autoload": { "psr-4": { From 42cdee0e605534b2772424f6ab677603d507efeb Mon Sep 17 00:00:00 2001 From: Pawel Skotnicki Date: Wed, 14 Feb 2024 14:50:43 +0100 Subject: [PATCH 13/16] Make AwsProvider a lazy service --- src/DependencyInjection/UecodeQPushExtension.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/DependencyInjection/UecodeQPushExtension.php b/src/DependencyInjection/UecodeQPushExtension.php index cab5f55..79d6e2f 100755 --- a/src/DependencyInjection/UecodeQPushExtension.php +++ b/src/DependencyInjection/UecodeQPushExtension.php @@ -123,6 +123,10 @@ public function load(array $configs, ContainerBuilder $container) } } + if ($isProviderAWS) { + $definition->setLazy(true); + } + $name = sprintf('uecode_qpush.%s', $queue); $container->setDefinition($name, $definition); From 5fbdea36667a458a92319517650d3b6e7baa4414 Mon Sep 17 00:00:00 2001 From: Manuel Reinhard Date: Wed, 22 May 2024 13:40:36 +0200 Subject: [PATCH 14/16] Treat queue attributes as string for AWS --- src/Provider/AwsProvider.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Provider/AwsProvider.php b/src/Provider/AwsProvider.php index f42632a..2f28a48 100755 --- a/src/Provider/AwsProvider.php +++ b/src/Provider/AwsProvider.php @@ -373,9 +373,9 @@ public function topicExists() public function createQueue() { $attributes = [ - 'VisibilityTimeout' => $this->options['message_timeout'], - 'MessageRetentionPeriod' => $this->options['message_expiration'], - 'ReceiveMessageWaitTimeSeconds' => $this->options['receive_wait_time'] + 'VisibilityTimeout' => (string) $this->options['message_timeout'], + 'MessageRetentionPeriod' => (string) $this->options['message_expiration'], + 'ReceiveMessageWaitTimeSeconds' => (string) $this->options['receive_wait_time'] ]; if ($this->isQueueFIFO()) { From 76861ac77a537232d5e5daf46e421a9fdbc5ad1f Mon Sep 17 00:00:00 2001 From: Tomasz Surowiec Date: Wed, 2 Apr 2025 09:14:22 +0200 Subject: [PATCH 15/16] [] prepare fork to work with Symfony 6 --- composer.json | 14 +++---- phpunit.xml.dist | 39 ++++++------------- src/DependencyInjection/Configuration.php | 13 ++++--- .../UecodeQPushExtension.php | 8 ++-- tests/EventListener/RequestListenerTest.php | 7 ++++ tests/Provider/SyncProviderTest.php | 2 +- 6 files changed, 38 insertions(+), 45 deletions(-) diff --git a/composer.json b/composer.json index 41a3e98..fd47478 100755 --- a/composer.json +++ b/composer.json @@ -6,17 +6,17 @@ "homepage": "https://github.com/ticketpark/qpush-bundle", "license": "Apache-2.0", "require": { - "php": ">=7.3", - "symfony/dependency-injection": "^4.0|^5.0", - "symfony/config": "^4.0|^5.0", - "symfony/http-kernel": "^4.0|^5.0", - "symfony/console": "^4.0|^5.0", + "php": ">=8.1", + "symfony/dependency-injection": "^5.0|^6.0", + "symfony/config": "^5.0|^6.0", + "symfony/http-kernel": "^5.0|^6.0", + "symfony/console": "^5.0|^6.0", "aws/aws-sdk-php": "~3.0", "doctrine/collections": "^1.6" }, "require-dev": { - "symfony/phpunit-bridge": "^4.0|^5.0", - "symfony/yaml": "^4.0|^5.0" + "symfony/phpunit-bridge": "^5.0|^6.0", + "symfony/yaml": "^5.0|^6.0" }, "autoload": { "psr-4": { diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 2b8f9b9..8d8a2a0 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,30 +1,13 @@ - - - - src/ - - - - - - ./tests/ - - - ./integration_tests/ - - - - - + + + + src/ + + + + + ./tests/ + + diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index ba1f7ac..49bebe5 100755 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -22,6 +22,9 @@ namespace Uecode\Bundle\QPushBundle\DependencyInjection; +use InvalidArgumentException; +use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; +use Symfony\Component\Config\Definition\Builder\NodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; @@ -30,7 +33,7 @@ */ class Configuration implements ConfigurationInterface { - public function getConfigTreeBuilder() + public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder('uecode_qpush'); @@ -45,7 +48,7 @@ public function getConfigTreeBuilder() return $treeBuilder; } - private function getProvidersNode() + private function getProvidersNode(): ArrayNodeDefinition|NodeDefinition { $treeBuilder = new TreeBuilder('providers'); $requirements = [ @@ -103,7 +106,7 @@ private function getProvidersNode() ->then(function (array $provider) use ($node, $requirements) { foreach ($requirements[$provider['driver']] as $requirement) { if (empty($provider[$requirement])) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( sprintf('%s queue providers must have a %s; none provided', $provider['driver'], $requirement) ); } @@ -117,7 +120,7 @@ private function getProvidersNode() return $node; } - private function getQueuesNode() + private function getQueuesNode(): ArrayNodeDefinition|NodeDefinition { $treeBuilder = new TreeBuilder('queues'); $node = $treeBuilder->getRootNode(); @@ -204,7 +207,7 @@ private function getQueuesNode() return $node; } - private function getSubscribersNode() + private function getSubscribersNode(): ArrayNodeDefinition|NodeDefinition { $treeBuilder = new TreeBuilder('subscribers'); $node = $treeBuilder->getRootNode(); diff --git a/src/DependencyInjection/UecodeQPushExtension.php b/src/DependencyInjection/UecodeQPushExtension.php index 79d6e2f..c71eca4 100755 --- a/src/DependencyInjection/UecodeQPushExtension.php +++ b/src/DependencyInjection/UecodeQPushExtension.php @@ -44,7 +44,7 @@ class UecodeQPushExtension extends Extension * * @throws RuntimeException|InvalidArgumentException|ServiceNotFoundException */ - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); @@ -145,7 +145,7 @@ public function load(array $configs, ContainerBuilder $container) * * @return Reference */ - private function createAwsClient($config, ContainerBuilder $container, $name) + private function createAwsClient($config, ContainerBuilder $container, $name): Reference { $service = sprintf('uecode_qpush.provider.%s', $name); @@ -197,7 +197,7 @@ private function createAwsClient($config, ContainerBuilder $container, $name) /** * @return Reference */ - private function createSyncClient() + private function createSyncClient(): Reference { return new Reference('event_dispatcher'); } @@ -207,7 +207,7 @@ private function createSyncClient() * * @return string */ - public function getAlias() + public function getAlias(): string { return 'uecode_qpush'; } diff --git a/tests/EventListener/RequestListenerTest.php b/tests/EventListener/RequestListenerTest.php index 752836c..a49aa18 100644 --- a/tests/EventListener/RequestListenerTest.php +++ b/tests/EventListener/RequestListenerTest.php @@ -22,6 +22,7 @@ namespace Uecode\Bundle\QPushBundle\Tests\EventListener; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; @@ -30,6 +31,7 @@ use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\KernelInterface; use Uecode\Bundle\QPushBundle\EventListener\RequestListener; use Uecode\Bundle\QPushBundle\Event\Events as QPushEvents; use Uecode\Bundle\QPushBundle\Event\NotificationEvent; @@ -49,6 +51,11 @@ class RequestListenerTest extends TestCase */ protected $event; + /** + * @var KernelInterface|MockObject + */ + private $kernel; + public function setUp(): void { $this->dispatcher = new EventDispatcher('UTF-8'); diff --git a/tests/Provider/SyncProviderTest.php b/tests/Provider/SyncProviderTest.php index 0aec12c..e8db279 100644 --- a/tests/Provider/SyncProviderTest.php +++ b/tests/Provider/SyncProviderTest.php @@ -44,8 +44,8 @@ public function testPublish() ->expects($this->once()) ->method('dispatch') ->with( + new IsInstanceOf('Uecode\Bundle\QPushBundle\Event\MessageEvent'), Events::Message($this->provider->getName()), - new IsInstanceOf('Uecode\Bundle\QPushBundle\Event\MessageEvent') ); $this->provider->publish(['foo' => 'bar']); From 56b82536551a54cf4823f70677eae056fd085668 Mon Sep 17 00:00:00 2001 From: Tomasz Surowiec Date: Thu, 10 Apr 2025 07:49:53 +0200 Subject: [PATCH 16/16] [] since the RegisterListenersPass doesn't allow configuration anymore, we need to start using default event_dispatcher's tags: `kernel.event_dispatcher` and `kernel.event_subscriber` --- README.md | 2 +- .../UecodeQPushExtension.php | 6 +++--- src/UecodeQPushBundle.php | 18 ------------------ 3 files changed, 4 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 783ba4c..df56c7a 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ services: my_example_service: class: My\Bundle\ExampleBundle\Service\ExampleService tags: - - { name: uecode_qpush.event_listener, event: my_queue_key.message_received, method: onMessageReceived } + - { name: kernel.event_listener, event: my_queue_key.message_received, method: onMessageReceived } ``` ###### Example diff --git a/src/DependencyInjection/UecodeQPushExtension.php b/src/DependencyInjection/UecodeQPushExtension.php index c71eca4..4950205 100755 --- a/src/DependencyInjection/UecodeQPushExtension.php +++ b/src/DependencyInjection/UecodeQPushExtension.php @@ -87,7 +87,7 @@ public function load(array $configs, ContainerBuilder $container): void $definition->setPublic(true); $definition ->addTag( - 'uecode_qpush.event_listener', + 'kernel.event_listener', [ 'event' => "{$queue}.on_notification", 'method' => "onNotification", @@ -95,7 +95,7 @@ public function load(array $configs, ContainerBuilder $container): void ] ) ->addTag( - 'uecode_qpush.event_listener', + 'kernel.event_listener', [ 'event' => "{$queue}.message_received", 'method' => "onMessageReceived", @@ -108,7 +108,7 @@ public function load(array $configs, ContainerBuilder $container): void if ($isQueueNameSet && $isProviderAWS) { $definition->addTag( - 'uecode_qpush.event_listener', + 'kernel.event_listener', [ 'event' => "{$values['options']['queue_name']}.on_notification", 'method' => "onNotification", diff --git a/src/UecodeQPushBundle.php b/src/UecodeQPushBundle.php index d78362a..67f42b6 100755 --- a/src/UecodeQPushBundle.php +++ b/src/UecodeQPushBundle.php @@ -40,22 +40,4 @@ public function __construct() // Setting extension to bypass alias convention check $this->extension = new UecodeQPushExtension(); } - - /** - * Adds the Compiler Passes for the QPushBundle - * - * @param ContainerBuilder $container - */ - public function build(ContainerBuilder $container) - { - parent::build($container); - - $container->addCompilerPass( - new RegisterListenersPass( - 'event_dispatcher', - 'uecode_qpush.event_listener', - 'uecode_qpush.event_subscriber' - ) - ); - } }