From e704da396ee6d294c4844f81d866ca7b7af6a740 Mon Sep 17 00:00:00 2001 From: "akihito.nakano" Date: Tue, 26 Sep 2017 21:32:34 +0900 Subject: [PATCH 001/108] Fix FlatFileDriver does not notice new messages --- src/Driver/FlatFileDriver.php | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/Driver/FlatFileDriver.php b/src/Driver/FlatFileDriver.php index a904bb9e..ebae8d20 100644 --- a/src/Driver/FlatFileDriver.php +++ b/src/Driver/FlatFileDriver.php @@ -94,10 +94,7 @@ public function popMessage($queueName, $duration = 5) $runtime = microtime(true) + $duration; $queueDir = $this->getQueueDirectory($queueName); - $it = new \GlobIterator($queueDir.DIRECTORY_SEPARATOR.'*.job', \FilesystemIterator::KEY_AS_FILENAME); - $files = array_keys(iterator_to_array($it)); - - natsort($files); + $files = $this->getJobFiles($queueName); while (microtime(true) < $runtime) { if ($files) { @@ -105,6 +102,9 @@ public function popMessage($queueName, $duration = 5) if (@rename($queueDir.DIRECTORY_SEPARATOR.$id, $queueDir.DIRECTORY_SEPARATOR.$id.'.proceed')) { return array(file_get_contents($queueDir.DIRECTORY_SEPARATOR.$id.'.proceed'), $id); } + } else { + // In order to notice that a new message received, update the list. + $files = $this->getJobFiles($queueName); } usleep(1000); @@ -225,4 +225,21 @@ private function getJobFilename($queueName) return $filename; } + + /** + * @param string $queueName + * + * @return string[] + */ + private function getJobFiles($queueName) + { + $it = new \GlobIterator( + $this->getQueueDirectory($queueName) . DIRECTORY_SEPARATOR . '*.job', + \FilesystemIterator::KEY_AS_FILENAME + ); + $files = array_keys(iterator_to_array($it)); + natsort($files); + + return $files; + } } From 777e16bf1b76030b52f0661bb487031aa1d47ab1 Mon Sep 17 00:00:00 2001 From: "akihito.nakano" Date: Mon, 6 Nov 2017 21:40:15 +0900 Subject: [PATCH 002/108] Add a test which reproduce #330 --- composer.json | 3 ++- tests/Driver/FlatFileDriverTest.php | 34 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index f6f9904b..d9ef52c8 100644 --- a/composer.json +++ b/composer.json @@ -27,7 +27,8 @@ "iron-io/iron_mq": "~4.0", "league/container": "~2.3", "queue-interop/queue-interop": "^0.6", - "queue-interop/amqp-interop": "^0.6" + "queue-interop/amqp-interop": "^0.6", + "ackintosh/snidel": "^0.10" }, "suggest": { "php-amqplib/php-amqplib": "Allow sending messages to an AMQP server using php-amqplib", diff --git a/tests/Driver/FlatFileDriverTest.php b/tests/Driver/FlatFileDriverTest.php index f1125334..6c8c5d1f 100644 --- a/tests/Driver/FlatFileDriverTest.php +++ b/tests/Driver/FlatFileDriverTest.php @@ -2,6 +2,7 @@ namespace Bernard\Tests\Driver; +use Ackintosh\Snidel; use Bernard\Driver\FlatFileDriver; /** @@ -92,6 +93,39 @@ public function testPopMessage() } } + public function testPopMessageWhichPushedAfterTheInitialCollect() + { + $this->driver->createQueue('send-newsletter'); + $snidel = new Snidel(); + + // Fork a process which pops message + $snidel->process( + function () { + list($message, ) = $this->driver->popMessage('send-newsletter', 10); + return $message; + }, + [], + 'popMessage' + ); + + // Fork another process which pushes message + $snidel->process( + function () { + // Push a message after the initial collect + sleep(5); + $this->driver->pushMessage('send-newsletter', 'test'); + }, + [], + 'pushMessage' + ); + + foreach ($snidel->results() as $result) { + if ($result->getTask()->getTag() === 'popMessage') { + $this->assertSame('test', $result->getReturn()); + } + } + } + public function testAcknowledgeMessage() { $this->driver->createQueue('send-newsletter'); From 6e7d758de3039c5102e15820d70705c4c5c956b2 Mon Sep 17 00:00:00 2001 From: "akihito.nakano" Date: Mon, 6 Nov 2017 22:43:12 +0900 Subject: [PATCH 003/108] Fix test fails with `--prefer-lowest` and hhvm --- composer.json | 2 +- tests/Driver/FlatFileDriverTest.php | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index d9ef52c8..c453841f 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ "league/container": "~2.3", "queue-interop/queue-interop": "^0.6", "queue-interop/amqp-interop": "^0.6", - "ackintosh/snidel": "^0.10" + "ackintosh/snidel": "^0.10.2" }, "suggest": { "php-amqplib/php-amqplib": "Allow sending messages to an AMQP server using php-amqplib", diff --git a/tests/Driver/FlatFileDriverTest.php b/tests/Driver/FlatFileDriverTest.php index 6c8c5d1f..3c54c38c 100644 --- a/tests/Driver/FlatFileDriverTest.php +++ b/tests/Driver/FlatFileDriverTest.php @@ -95,6 +95,11 @@ public function testPopMessage() public function testPopMessageWhichPushedAfterTheInitialCollect() { + // Snidel is only supported on PHP. + if (defined('HHVM_VERSION')) { + $this->markTestSkipped(); + } + $this->driver->createQueue('send-newsletter'); $snidel = new Snidel(); From fde500e6b9b3185386e80d0734be0d7e5b71713f Mon Sep 17 00:00:00 2001 From: "akihito.nakano" Date: Tue, 7 Nov 2017 00:09:20 +0900 Subject: [PATCH 004/108] Tweak skip message --- tests/Driver/FlatFileDriverTest.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/Driver/FlatFileDriverTest.php b/tests/Driver/FlatFileDriverTest.php index 3c54c38c..10ed2019 100644 --- a/tests/Driver/FlatFileDriverTest.php +++ b/tests/Driver/FlatFileDriverTest.php @@ -95,9 +95,8 @@ public function testPopMessage() public function testPopMessageWhichPushedAfterTheInitialCollect() { - // Snidel is only supported on PHP. if (defined('HHVM_VERSION')) { - $this->markTestSkipped(); + $this->markTestSkipped('Snidel is only supported on PHP.'); } $this->driver->createQueue('send-newsletter'); From 6e6ad0f2fd1a80ddbed2c9515e6aa24354b078e5 Mon Sep 17 00:00:00 2001 From: "akihito.nakano" Date: Sun, 12 Nov 2017 12:10:24 +0900 Subject: [PATCH 005/108] Ignore .idea --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 5e3bf393..f021de7c 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ vendor phpunit.xml coverage _build +.idea From 7d7dd036d742a97664d0602d01437a9282fa5c59 Mon Sep 17 00:00:00 2001 From: "akihito.nakano" Date: Sun, 12 Nov 2017 12:37:58 +0900 Subject: [PATCH 006/108] Improve make the dependencies minimum --- composer.json | 3 +- tests/Driver/FlatFileDriverTest.php | 47 +++++++++-------------------- 2 files changed, 16 insertions(+), 34 deletions(-) diff --git a/composer.json b/composer.json index c453841f..f6f9904b 100644 --- a/composer.json +++ b/composer.json @@ -27,8 +27,7 @@ "iron-io/iron_mq": "~4.0", "league/container": "~2.3", "queue-interop/queue-interop": "^0.6", - "queue-interop/amqp-interop": "^0.6", - "ackintosh/snidel": "^0.10.2" + "queue-interop/amqp-interop": "^0.6" }, "suggest": { "php-amqplib/php-amqplib": "Allow sending messages to an AMQP server using php-amqplib", diff --git a/tests/Driver/FlatFileDriverTest.php b/tests/Driver/FlatFileDriverTest.php index 10ed2019..28bf4d49 100644 --- a/tests/Driver/FlatFileDriverTest.php +++ b/tests/Driver/FlatFileDriverTest.php @@ -2,7 +2,6 @@ namespace Bernard\Tests\Driver; -use Ackintosh\Snidel; use Bernard\Driver\FlatFileDriver; /** @@ -95,39 +94,23 @@ public function testPopMessage() public function testPopMessageWhichPushedAfterTheInitialCollect() { - if (defined('HHVM_VERSION')) { - $this->markTestSkipped('Snidel is only supported on PHP.'); - } - $this->driver->createQueue('send-newsletter'); - $snidel = new Snidel(); - - // Fork a process which pops message - $snidel->process( - function () { - list($message, ) = $this->driver->popMessage('send-newsletter', 10); - return $message; - }, - [], - 'popMessage' - ); - - // Fork another process which pushes message - $snidel->process( - function () { - // Push a message after the initial collect - sleep(5); - $this->driver->pushMessage('send-newsletter', 'test'); - }, - [], - 'pushMessage' - ); - - foreach ($snidel->results() as $result) { - if ($result->getTask()->getTag() === 'popMessage') { - $this->assertSame('test', $result->getReturn()); - } + + $pid = pcntl_fork(); + + if ($pid === -1) { + $this->fail('Failed to fork the currently running process: ' . pcntl_strerror(pcntl_get_last_error())); + } elseif ($pid === 0) { + // Child process pushes a message after the initial collect + sleep(5); + $this->driver->pushMessage('send-newsletter', 'test'); + exit; } + + list($message, ) = $this->driver->popMessage('send-newsletter', 10); + $this->assertSame('test', $message); + + pcntl_waitpid($pid, $status); } public function testAcknowledgeMessage() From 7c819f19899b6c3402d6cc02ea51f78c36a276d1 Mon Sep 17 00:00:00 2001 From: ackintosh Date: Mon, 13 Nov 2017 13:31:23 +0900 Subject: [PATCH 007/108] Remove ignores which is not project specific --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index f021de7c..5e3bf393 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,3 @@ vendor phpunit.xml coverage _build -.idea From 828920b88e103d766491bb17b41858c7d3974e56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Wed, 14 Feb 2018 01:54:04 +0100 Subject: [PATCH 008/108] Relocate drivers (#337) * InMemory queue implementation * Phpamqp driver implementation * Renamed driver from PhpAmqp to Amqp * Move Pheanstalk driver to new namespace * Move Redis drivers to new namespace * Move Doctrine driver to new namespace * Move IronMQ driver to new namespace * Move SQS driver to new namespace * Move MongoDB driver to new namespace * Move AppEngine driver to new namespace * Move the FlatFile driver to new namespace * Move Interop driver to new namespace * Update documentation --- doc/drivers.rst | 52 ++++----- example/doctrine.php | 6 +- example/file.php | 4 +- example/ironmq.php | 4 +- example/pheanstalk.php | 4 +- example/phpredis.php | 4 +- example/predis.php | 4 +- example/sqs.php | 4 +- .../{PhpAmqpDriver.php => Amqp/Driver.php} | 6 +- .../Driver.php} | 10 +- .../Doctrine/Command}/AbstractCommand.php | 4 +- .../Doctrine/Command}/CreateCommand.php | 2 +- .../Doctrine/Command}/DropCommand.php | 2 +- .../Doctrine/Command}/UpdateCommand.php | 2 +- .../Doctrine/ConnectionListener.php | 2 +- .../Driver.php} | 8 +- src/{ => Driver}/Doctrine/MessagesSchema.php | 2 +- .../Driver.php} | 4 +- src/Driver/InMemory/Driver.php | 101 ++++++++++++++++++ .../{InteropDriver.php => Interop/Driver.php} | 6 +- .../{IronMqDriver.php => IronMQ/Driver.php} | 9 +- .../{MongoDBDriver.php => MongoDB/Driver.php} | 4 +- .../Driver.php} | 6 +- .../Driver.php} | 4 +- .../{PredisDriver.php => Predis/Driver.php} | 6 +- src/Driver/{SqsDriver.php => Sqs/Driver.php} | 11 +- .../DriverTest.php} | 32 +++--- .../DriverTest.php} | 11 +- .../AbstractDriverTest.php} | 16 +-- .../Doctrine/Command}/AbstractCommandTest.php | 6 +- .../Doctrine/Command}/BaseCommandTest.php | 4 +- .../Doctrine/Command}/CreateCommandTest.php | 2 +- .../Doctrine/Command}/DropCommandTest.php | 2 +- .../Doctrine/Command}/UpdateCommandTest.php | 2 +- .../Doctrine/ConnectionListenerTest.php | 4 +- .../MySQLDriverTest.php} | 8 +- .../PostgreSQLDriverTest.php} | 8 +- .../SQLiteDriverTest.php} | 8 +- .../DriverTest.php} | 20 ++-- tests/Driver/InMemory/DriverTest.php | 32 ++++++ .../DriverTest.php} | 32 +++--- .../DriverTest.php} | 22 ++-- .../DriverFunctionalTest.php} | 15 ++- .../DriverTest.php} | 13 ++- .../DriverTest.php} | 23 ++-- .../DriverTest.php} | 10 +- .../DriverTest.php} | 11 +- .../{SqsDriverTest.php => Sqs/DriverTest.php} | 25 +++-- tests/Fixtures/PushTask.php | 2 +- 49 files changed, 366 insertions(+), 213 deletions(-) rename src/Driver/{PhpAmqpDriver.php => Amqp/Driver.php} (97%) rename src/Driver/{AppEngineDriver.php => AppEngine/Driver.php} (89%) rename src/{Command/Doctrine => Driver/Doctrine/Command}/AbstractCommand.php (96%) rename src/{Command/Doctrine => Driver/Doctrine/Command}/CreateCommand.php (93%) rename src/{Command/Doctrine => Driver/Doctrine/Command}/DropCommand.php (93%) rename src/{Command/Doctrine => Driver/Doctrine/Command}/UpdateCommand.php (93%) rename src/{ => Driver}/Doctrine/ConnectionListener.php (97%) rename src/Driver/{DoctrineDriver.php => Doctrine/Driver.php} (96%) rename src/{ => Driver}/Doctrine/MessagesSchema.php (97%) rename src/Driver/{FlatFileDriver.php => FlatFile/Driver.php} (98%) create mode 100644 src/Driver/InMemory/Driver.php rename src/Driver/{InteropDriver.php => Interop/Driver.php} (97%) rename src/Driver/{IronMqDriver.php => IronMQ/Driver.php} (94%) rename src/Driver/{MongoDBDriver.php => MongoDB/Driver.php} (97%) rename src/Driver/{PheanstalkDriver.php => Pheanstalk/Driver.php} (94%) rename src/Driver/{PhpRedisDriver.php => PhpRedis/Driver.php} (97%) rename src/Driver/{PredisDriver.php => Predis/Driver.php} (91%) rename src/Driver/{SqsDriver.php => Sqs/Driver.php} (96%) rename tests/Driver/{PhpAmqpDriverTest.php => Amqp/DriverTest.php} (85%) rename tests/Driver/{AppEngineDriverTest.php => AppEngine/DriverTest.php} (87%) rename tests/Driver/{AbstractDoctrineDriverTest.php => Doctrine/AbstractDriverTest.php} (93%) rename tests/{Command/Doctrine => Driver/Doctrine/Command}/AbstractCommandTest.php (91%) rename tests/{Command/Doctrine => Driver/Doctrine/Command}/BaseCommandTest.php (93%) rename tests/{Command/Doctrine => Driver/Doctrine/Command}/CreateCommandTest.php (89%) rename tests/{Command/Doctrine => Driver/Doctrine/Command}/DropCommandTest.php (89%) rename tests/{Command/Doctrine => Driver/Doctrine/Command}/UpdateCommandTest.php (89%) rename tests/{ => Driver}/Doctrine/ConnectionListenerTest.php (94%) rename tests/Driver/{MySQLDoctrineDriverTest.php => Doctrine/MySQLDriverTest.php} (78%) rename tests/Driver/{PostgreSQLDoctrineDriverTest.php => Doctrine/PostgreSQLDriverTest.php} (76%) rename tests/Driver/{SQLiteDoctrineDriverTest.php => Doctrine/SQLiteDriverTest.php} (74%) rename tests/Driver/{FlatFileDriverTest.php => FlatFile/DriverTest.php} (92%) create mode 100644 tests/Driver/InMemory/DriverTest.php rename tests/Driver/{InteropDriverTest.php => Interop/DriverTest.php} (89%) rename tests/Driver/{IronMqDriverTest.php => IronMQ/DriverTest.php} (89%) rename tests/Driver/{MongoDBDriverFunctionalTest.php => MongoDB/DriverFunctionalTest.php} (93%) rename tests/Driver/{MongoDBDriverTest.php => MongoDB/DriverTest.php} (94%) rename tests/Driver/{PheanstalkDriverTest.php => Pheanstalk/DriverTest.php} (83%) rename tests/Driver/{PhpRedisDriverTest.php => PhpRedis/DriverTest.php} (92%) rename tests/Driver/{PredisDriverTest.php => Predis/DriverTest.php} (78%) rename tests/Driver/{SqsDriverTest.php => Sqs/DriverTest.php} (93%) diff --git a/doc/drivers.rst b/doc/drivers.rst index 23e15a77..7ccbc99b 100644 --- a/doc/drivers.rst +++ b/doc/drivers.rst @@ -38,9 +38,9 @@ preconfigured. '/url_endpoint', )); @@ -106,7 +106,7 @@ as appropriate for your use case. 'your-ironmq-token', @@ -238,10 +238,10 @@ in the drivers constructor. )); - $driver = new IronMqDriver($connection); + $driver = new Driver($connection); // or with a prefetching number - $driver = new IronMqDriver($connection, 5); + $driver = new Driver($connection, 5); It is also possible to use push queues with some additional logic. Basically, it is needed to deserialize the message in the request and route it to the @@ -296,7 +296,7 @@ corresponding to the queue and message collections, respectively. selectCollection('bernardDatabase', 'queues'), $mongoClient->selectCollection('bernardDatabase', 'messages'), ); @@ -341,12 +341,12 @@ Requires the installation of pda/pheanstalk. Add the following to your connect('127.0.0.1', 6379); $redis->setOption(Redis::OPT_PREFIX, 'bernard:'); - $driver = new PhpRedisDriver($redis); + $driver = new Driver($redis); Predis ------ @@ -415,14 +415,14 @@ Requires the installation of predis. Add the following to your 'bernard:', )); - $driver = new PredisDriver($predis); + $driver = new Driver($predis); Amazon SQS ---------- @@ -459,7 +459,7 @@ require a HTTP request to amazon to be resolved. 'your-aws-access-key', @@ -467,13 +467,13 @@ require a HTTP request to amazon to be resolved. 'region' => 'the-aws-region-you-choose' )); - $driver = new SqsDriver($connection); + $driver = new Driver($connection); // or with prefetching - $driver = new SqsDriver($connection, array(), 5); + $driver = new Driver($connection, array(), 5); // or with aliased queue urls - $driver = new SqsDriver($connection, array( + $driver = new Driver($connection, array( 'queue-name' => 'queue-url', )); @@ -495,7 +495,7 @@ For example we choose enqueue/fs one to demonstrate how it is working. createContext(); diff --git a/example/doctrine.php b/example/doctrine.php index 554b732a..a28f0e10 100644 --- a/example/doctrine.php +++ b/example/doctrine.php @@ -1,6 +1,6 @@ 'pdo_mysql', )); - $doctrineDriver = new DoctrineDriver($connection); + $doctrineDriver = new Driver($connection); //Don't do this in your application. Use a database set up script instead. try { @@ -24,7 +24,7 @@ function get_driver() { } catch (\Exception $ex) { $schema = new \Doctrine\DBAL\Schema\Schema(); - \Bernard\Doctrine\MessagesSchema::create($schema); + \Bernard\Driver\Doctrine\MessagesSchema::create($schema); array_map(array($connection, 'executeQuery'), $schema->toSql($connection->getDatabasePlatform())); } diff --git a/example/file.php b/example/file.php index 699ed4ef..6d721cf6 100644 --- a/example/file.php +++ b/example/file.php @@ -1,6 +1,6 @@ getenv('IRONMQ_PROJECT_ID'), )); - return new IronMqDriver($ironmq); + return new Driver($ironmq); } if (!getenv('IRONMQ_TOKEN') || !getenv('IRONMQ_PROJECT_ID')) { diff --git a/example/pheanstalk.php b/example/pheanstalk.php index 2e95de4f..aabe72ca 100644 --- a/example/pheanstalk.php +++ b/example/pheanstalk.php @@ -1,7 +1,7 @@ connect('localhost'); $redis->setOption(Redis::OPT_PREFIX, 'bernard:'); - return new PhpRedisDriver($redis); + return new Driver($redis); } require 'bootstrap.php'; diff --git a/example/predis.php b/example/predis.php index 6d38b587..169201ad 100644 --- a/example/predis.php +++ b/example/predis.php @@ -1,14 +1,14 @@ 'bernard:', ))); } diff --git a/example/sqs.php b/example/sqs.php index 1e1ae06a..3f31d2d4 100644 --- a/example/sqs.php +++ b/example/sqs.php @@ -1,7 +1,7 @@ getenv('SQS_REGION') )); - return new SqsDriver($sqs); + return new Driver($sqs); } if (!getenv('ACCESS_KEY') || !getenv('SECRET_KEY') || !getenv('SQS_REGION')) { diff --git a/src/Driver/PhpAmqpDriver.php b/src/Driver/Amqp/Driver.php similarity index 97% rename from src/Driver/PhpAmqpDriver.php rename to src/Driver/Amqp/Driver.php index 402df9f5..2ad1e01b 100644 --- a/src/Driver/PhpAmqpDriver.php +++ b/src/Driver/Amqp/Driver.php @@ -1,13 +1,12 @@ queueMap[$queueName])) { return $this->queueMap[$queueName]; diff --git a/src/Command/Doctrine/AbstractCommand.php b/src/Driver/Doctrine/Command/AbstractCommand.php similarity index 96% rename from src/Command/Doctrine/AbstractCommand.php rename to src/Driver/Doctrine/Command/AbstractCommand.php index a2850751..75b2e373 100644 --- a/src/Command/Doctrine/AbstractCommand.php +++ b/src/Driver/Doctrine/Command/AbstractCommand.php @@ -1,8 +1,8 @@ */ -class FlatFileDriver implements \Bernard\Driver +class Driver implements \Bernard\Driver { private $baseDirectory; diff --git a/src/Driver/InMemory/Driver.php b/src/Driver/InMemory/Driver.php new file mode 100644 index 00000000..8c7af5f6 --- /dev/null +++ b/src/Driver/InMemory/Driver.php @@ -0,0 +1,101 @@ + + */ +final class Driver implements \Bernard\Driver +{ + private $queues = []; + + /** + * {@inheritdoc} + */ + public function listQueues() + { + return array_keys($this->queues); + } + + /** + * {@inheritdoc} + */ + public function createQueue($queueName) + { + if (!array_key_exists($queueName, $this->queues)) { + $this->queues[$queueName] = []; + } + } + + /** + * {@inheritdoc} + */ + public function countMessages($queueName) + { + if (array_key_exists($queueName, $this->queues)) { + return count($this->queues[$queueName]); + } + + return 0; + } + + /** + * {@inheritdoc} + */ + public function pushMessage($queueName, $message) + { + $this->queues[$queueName][] = $message; + } + + /** + * {@inheritdoc} + */ + public function popMessage($queueName, $duration = 5) + { + if (!array_key_exists($queueName, $this->queues) || count($this->queues[$queueName]) < 1) { + return [null, null]; + } + + return [array_shift($this->queues[$queueName]), null]; + } + + /** + * {@inheritdoc} + */ + public function acknowledgeMessage($queueName, $receipt) + { + // Noop + } + + /** + * {@inheritdoc} + */ + public function peekQueue($queueName, $index = 0, $limit = 20) + { + if (array_key_exists($queueName, $this->queues)) { + return array_slice($this->queues[$queueName], $index, $limit); + } + + return null; + } + + /** + * {@inheritdoc} + */ + public function removeQueue($queueName) + { + if (array_key_exists($queueName, $this->queues)) { + unset($this->queues[$queueName]); + } + } + + /** + * {@inheritdoc} + */ + public function info() + { + return []; + } +} diff --git a/src/Driver/InteropDriver.php b/src/Driver/Interop/Driver.php similarity index 97% rename from src/Driver/InteropDriver.php rename to src/Driver/Interop/Driver.php index 4b087d78..acf580dc 100644 --- a/src/Driver/InteropDriver.php +++ b/src/Driver/Interop/Driver.php @@ -1,13 +1,13 @@ queueUrls[$queueName])) { return $this->queueUrls[$queueName]; diff --git a/tests/Driver/PhpAmqpDriverTest.php b/tests/Driver/Amqp/DriverTest.php similarity index 85% rename from tests/Driver/PhpAmqpDriverTest.php rename to tests/Driver/Amqp/DriverTest.php index ee899067..2416ffb2 100644 --- a/tests/Driver/PhpAmqpDriverTest.php +++ b/tests/Driver/Amqp/DriverTest.php @@ -1,26 +1,27 @@ method('channel') ->willReturn($this->phpAmqpChannel); - $this->driver = new PhpAmqpDriver($this->phpAmqpConnection, self::EXCHANGE_NAME); + $this->driver = new Driver($this->phpAmqpConnection, self::EXCHANGE_NAME); } public function testItImplementsDriverInterface() @@ -65,18 +66,15 @@ public function testItCreatesQueue() $this->phpAmqpChannel ->expects($this->once()) ->method('exchange_declare') - ->with(self::EXCHANGE_NAME, 'direct', false, true, false) - ; + ->with(self::EXCHANGE_NAME, 'direct', false, true, false); $this->phpAmqpChannel ->expects($this->once()) ->method('queue_declare') - ->with('foo-queue', false, true, false, false) - ; + ->with('foo-queue', false, true, false, false); $this->phpAmqpChannel ->expects($this->once()) ->method('queue_bind') - ->with('foo-queue', self::EXCHANGE_NAME, 'foo-queue') - ; + ->with('foo-queue', self::EXCHANGE_NAME, 'foo-queue'); $this->driver->createQueue('foo-queue'); } @@ -87,8 +85,8 @@ public function testItPushesMessages() ->expects($this->once()) ->method('basic_publish') ->with( - $this->callback(function(AMQPMessage $message) { - return $message->body == 'dummy push message'; + $this->callback(function (AMQPMessage $message) { + return $message->body === 'dummy push message'; }), self::EXCHANGE_NAME, 'not-relevant' @@ -98,7 +96,7 @@ public function testItPushesMessages() public function testItUsesDefaultParameters() { - $this->driver = new PhpAmqpDriver( + $this->driver = new Driver( $this->phpAmqpConnection, self::EXCHANGE_NAME, array('delivery_mode' => 2) @@ -108,7 +106,7 @@ public function testItUsesDefaultParameters() ->expects($this->once()) ->method('basic_publish') ->with( - $this->callback(function(AMQPMessage $message) { + $this->callback(function (AMQPMessage $message) { return $message->get('delivery_mode') === 2; }), self::EXCHANGE_NAME, diff --git a/tests/Driver/AppEngineDriverTest.php b/tests/Driver/AppEngine/DriverTest.php similarity index 87% rename from tests/Driver/AppEngineDriverTest.php rename to tests/Driver/AppEngine/DriverTest.php index 40342295..3efceb0b 100644 --- a/tests/Driver/AppEngineDriverTest.php +++ b/tests/Driver/AppEngine/DriverTest.php @@ -1,12 +1,15 @@ driver = new AppEngineDriver(array( + $this->driver = new Driver(array( 'send-newsletter' => '/url_endpoint', )); } diff --git a/tests/Driver/AbstractDoctrineDriverTest.php b/tests/Driver/Doctrine/AbstractDriverTest.php similarity index 93% rename from tests/Driver/AbstractDoctrineDriverTest.php rename to tests/Driver/Doctrine/AbstractDriverTest.php index 1ec32747..d280be3e 100644 --- a/tests/Driver/AbstractDoctrineDriverTest.php +++ b/tests/Driver/Doctrine/AbstractDriverTest.php @@ -1,13 +1,13 @@ setUpDatabase(); - $this->driver = new DoctrineDriver($this->connection); + $this->driver = new Driver($this->connection); } protected function tearDown() @@ -171,10 +171,10 @@ protected function setUpDatabase() /** * @return \Doctrine\DBAL\Connection */ - protected abstract function createConnection(); + abstract protected function createConnection(); /** * @return bool */ - protected abstract function isSupported(); + abstract protected function isSupported(); } diff --git a/tests/Command/Doctrine/AbstractCommandTest.php b/tests/Driver/Doctrine/Command/AbstractCommandTest.php similarity index 91% rename from tests/Command/Doctrine/AbstractCommandTest.php rename to tests/Driver/Doctrine/Command/AbstractCommandTest.php index 570e9733..b85d4cbb 100644 --- a/tests/Command/Doctrine/AbstractCommandTest.php +++ b/tests/Driver/Doctrine/Command/AbstractCommandTest.php @@ -1,8 +1,8 @@ method('getConnection') ->will($this->returnValue($connection)); - $this->command = $this->getMockBuilder('Bernard\\Command\\Doctrine\\AbstractCommand') + $this->command = $this->getMockBuilder(AbstractCommand::class) ->setMethods(['getSql', 'applySql', 'getHelper']) ->setConstructorArgs(['abstract']) ->getMock(); diff --git a/tests/Command/Doctrine/BaseCommandTest.php b/tests/Driver/Doctrine/Command/BaseCommandTest.php similarity index 93% rename from tests/Command/Doctrine/BaseCommandTest.php rename to tests/Driver/Doctrine/Command/BaseCommandTest.php index f8441a1f..0d0c312a 100644 --- a/tests/Command/Doctrine/BaseCommandTest.php +++ b/tests/Driver/Doctrine/Command/BaseCommandTest.php @@ -1,6 +1,6 @@ method('getConnection') ->will($this->returnValue($connection)); - $this->command = $this->getMockBuilder('Bernard\\Command\\Doctrine\\' . $this->getShortClassName()) + $this->command = $this->getMockBuilder('Bernard\\Driver\\Doctrine\\Command\\' . $this->getShortClassName()) ->setMethods(['getSynchronizer', 'getHelper']) ->setConstructorArgs([$connection]) ->getMock(); diff --git a/tests/Command/Doctrine/CreateCommandTest.php b/tests/Driver/Doctrine/Command/CreateCommandTest.php similarity index 89% rename from tests/Command/Doctrine/CreateCommandTest.php rename to tests/Driver/Doctrine/Command/CreateCommandTest.php index 95929b83..1e31381a 100644 --- a/tests/Command/Doctrine/CreateCommandTest.php +++ b/tests/Driver/Doctrine/Command/CreateCommandTest.php @@ -1,6 +1,6 @@ */ -class FlatFileDriverTest extends \PHPUnit\Framework\TestCase +class DriverTest extends \PHPUnit\Framework\TestCase { /** - * @var FlatFileDriver + * @var Driver */ private $driver; @@ -22,7 +22,7 @@ protected function setUp() mkdir($this->baseDir, 0777, true); } - $this->driver = new FlatFileDriver($this->baseDir); + $this->driver = new Driver($this->baseDir); } protected function tearDown() @@ -73,7 +73,7 @@ public function testPushMessage() public function testPushMessagePermissions() { - $this->driver = new FlatFileDriver($this->baseDir, 0770); + $this->driver = new Driver($this->baseDir, 0770); $this->testPushMessage(); $this->assertEquals('0770', substr(sprintf('%o', fileperms($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'.\DIRECTORY_SEPARATOR.'1.job')), -4)); } @@ -117,18 +117,18 @@ public function testPeekQueue() $this->assertCount(10, glob($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'.\DIRECTORY_SEPARATOR.'*.job')); } - + public function testListQueues() { $this->driver->createQueue('send-newsletter-1'); - + $this->driver->createQueue('send-newsletter-2'); $this->driver->pushMessage('send-newsletter-2', 'job #1'); - + $this->driver->createQueue('send-newsletter-3'); $this->driver->pushMessage('send-newsletter-3', 'job #1'); $this->driver->pushMessage('send-newsletter-3', 'job #2'); - + $this->assertCount(3, $this->driver->listQueues()); } } diff --git a/tests/Driver/InMemory/DriverTest.php b/tests/Driver/InMemory/DriverTest.php new file mode 100644 index 00000000..5c7dd15e --- /dev/null +++ b/tests/Driver/InMemory/DriverTest.php @@ -0,0 +1,32 @@ + + */ +final class DriverTest extends \PHPUnit\Framework\TestCase +{ + /** + * @var Driver + */ + private $driver; + + protected function setUp() + { + $this->driver = new Driver(); + } + + /** + *@test + */ + function it_lists_queues() + { + $this->driver->createQueue('queue1'); + $this->driver->createQueue('queue2'); + + $this->assertEquals(['queue1', 'queue2'], $this->driver->listQueues()); + } +} diff --git a/tests/Driver/InteropDriverTest.php b/tests/Driver/Interop/DriverTest.php similarity index 89% rename from tests/Driver/InteropDriverTest.php rename to tests/Driver/Interop/DriverTest.php index 0755b919..79cfed9f 100644 --- a/tests/Driver/InteropDriverTest.php +++ b/tests/Driver/Interop/DriverTest.php @@ -1,8 +1,8 @@ assertInstanceOf('Bernard\Driver', new InteropDriver($this->createInteropContextMock())); + $this->assertInstanceOf('Bernard\Driver', new Driver($this->createInteropContextMock())); } public function testListQueuesMethodDoesNothingAndAlwaysReturnEmptyArray() { - $driver = new InteropDriver($this->createInteropContextMock()); + $driver = new Driver($this->createInteropContextMock()); $this->assertSame([], $driver->listQueues()); } public function testCreateQueueMethodDoesNothingAndAlwaysReturnNull() { - $driver = new InteropDriver($this->createInteropContextMock()); + $driver = new Driver($this->createInteropContextMock()); $this->assertNull($driver->createQueue('aQueueName')); } @@ -63,7 +63,7 @@ public function testPushMessageMethodPublishMessageToQueueUsingInteropProducer() ->willReturn($producer) ; - $driver = new InteropDriver($context); + $driver = new Driver($context); $driver->pushMessage('theQueueName', 'theBody'); } @@ -94,7 +94,7 @@ public function testPopMessageReturnNullIfInteropConsumerReturnNothingOnReceive( ->willReturn($consumer) ; - $driver = new InteropDriver($context); + $driver = new Driver($context); $this->assertNull($driver->popMessage('theQueueName')); } @@ -131,7 +131,7 @@ public function testPopMessageReturnArrayWithBodyAndInteropMessage() ->willReturn($consumer) ; - $driver = new InteropDriver($context); + $driver = new Driver($context); $this->assertSame( ['theBody', $message], @@ -170,7 +170,7 @@ public function testAcknowledgeMessage() ->willReturn($consumer) ; - $driver = new InteropDriver($context); + $driver = new Driver($context); $result = $driver->popMessage('theQueueName'); @@ -182,21 +182,21 @@ public function testAcknowledgeMessage() public function testPeekQueueMethodDoesNothingAndAlwaysReturnEmptyArray() { - $driver = new InteropDriver($this->createInteropContextMock()); + $driver = new Driver($this->createInteropContextMock()); $this->assertSame([], $driver->peekQueue('aQueueName')); } public function testRemoveQueueMethodDoesNothingAndAlwaysReturnNull() { - $driver = new InteropDriver($this->createInteropContextMock()); + $driver = new Driver($this->createInteropContextMock()); $this->assertNull($driver->removeQueue('aQueueName')); } public function testInfoMethodDoesNothingAndAlwaysReturnEmptyArray() { - $driver = new InteropDriver($this->createInteropContextMock()); + $driver = new Driver($this->createInteropContextMock()); $this->assertNull($driver->removeQueue('aQueueName')); } @@ -223,7 +223,7 @@ public function testCreateQueueMethodShouldDeclareAmqpQueue() ->with($this->identicalTo($queue)) ; - $driver = new InteropDriver($context); + $driver = new Driver($context); $this->assertNull($driver->createQueue('theQueueName')); } @@ -250,7 +250,7 @@ public function testDeleteQueueMethodShouldCallDeleteQueueMethodOnAmqpContext() ->with($this->identicalTo($queue)) ; - $driver = new InteropDriver($context); + $driver = new Driver($context); $this->assertNull($driver->removeQueue('theQueueName')); } @@ -273,7 +273,7 @@ public function testCountMessagesMethodShouldUseCountFromAmqpDeclareQueueResult( ->willReturn(123) ; - $driver = new InteropDriver($context); + $driver = new Driver($context); $this->assertSame(123, $driver->countMessages('theQueueName')); } diff --git a/tests/Driver/IronMqDriverTest.php b/tests/Driver/IronMQ/DriverTest.php similarity index 89% rename from tests/Driver/IronMqDriverTest.php rename to tests/Driver/IronMQ/DriverTest.php index 6b9a9fb5..73d9e8fb 100644 --- a/tests/Driver/IronMqDriverTest.php +++ b/tests/Driver/IronMQ/DriverTest.php @@ -1,14 +1,22 @@ ironmq = $this->getMockBuilder('\IronMQ\IronMQ') + $this->ironmq = $this->getMockBuilder(IronMQ::class) ->setMethods(array( 'getQueue', 'getQueues', @@ -21,12 +29,12 @@ public function setUp() ->disableOriginalConstructor() ->getMock(); - $this->driver = new IronMqDriver($this->ironmq); + $this->driver = new Driver($this->ironmq); } public function testItExposesInfo() { - $driver = new IronMqDriver($this->ironmq, 10); + $driver = new Driver($this->ironmq, 10); $this->assertEquals(array('prefetch' => 10), $driver->info()); $this->assertEquals(array('prefetch' => 2), $this->driver->info()); @@ -34,7 +42,7 @@ public function testItExposesInfo() public function testItImplementsDriverInterface() { - $this->assertInstanceOf('Bernard\Driver\AbstractPrefetchDriver', $this->driver); + $this->assertInstanceOf(AbstractPrefetchDriver::class, $this->driver); } public function testItCountsNumberOfMessagesInQueue() diff --git a/tests/Driver/MongoDBDriverFunctionalTest.php b/tests/Driver/MongoDB/DriverFunctionalTest.php similarity index 93% rename from tests/Driver/MongoDBDriverFunctionalTest.php rename to tests/Driver/MongoDB/DriverFunctionalTest.php index e1e8cd2e..593b7483 100644 --- a/tests/Driver/MongoDBDriverFunctionalTest.php +++ b/tests/Driver/MongoDB/DriverFunctionalTest.php @@ -1,24 +1,29 @@ queues = $mongoClient->selectCollection(self::DATABASE, self::QUEUES); $this->messages = $mongoClient->selectCollection(self::DATABASE, self::MESSAGES); - $this->driver = new MongoDBDriver($this->queues, $this->messages); + $this->driver = new Driver($this->queues, $this->messages); } public function tearDown() diff --git a/tests/Driver/MongoDBDriverTest.php b/tests/Driver/MongoDB/DriverTest.php similarity index 94% rename from tests/Driver/MongoDBDriverTest.php rename to tests/Driver/MongoDB/DriverTest.php index 3ce34143..14d3a0e8 100644 --- a/tests/Driver/MongoDBDriverTest.php +++ b/tests/Driver/MongoDB/DriverTest.php @@ -1,16 +1,21 @@ queues = $this->getMockMongoCollection(); $this->messages = $this->getMockMongoCollection(); - $this->driver = new MongoDBDriver($this->queues, $this->messages); + $this->driver = new Driver($this->queues, $this->messages); } public function testListQueues() diff --git a/tests/Driver/PheanstalkDriverTest.php b/tests/Driver/Pheanstalk/DriverTest.php similarity index 83% rename from tests/Driver/PheanstalkDriverTest.php rename to tests/Driver/Pheanstalk/DriverTest.php index 3545f9c0..de330620 100644 --- a/tests/Driver/PheanstalkDriverTest.php +++ b/tests/Driver/Pheanstalk/DriverTest.php @@ -1,15 +1,22 @@ pheanstalk = $this->getMockBuilder('Pheanstalk\Pheanstalk') + $this->pheanstalk = $this->getMockBuilder(Pheanstalk::class) ->setMethods(array( 'listTubes', 'statsTube', @@ -21,12 +28,12 @@ public function setUp() ->disableOriginalConstructor() ->getMock(); - $this->driver = new PheanstalkDriver($this->pheanstalk); + $this->driver = new Driver($this->pheanstalk); } public function testItExposesInfo() { - $driver = new PheanstalkDriver($this->pheanstalk); + $driver = new Driver($this->pheanstalk); $info = new \ArrayObject(array('info' => true)); @@ -38,7 +45,7 @@ public function testItExposesInfo() public function testItImplementsDriverInterface() { - $this->assertInstanceOf('Bernard\Driver', $this->driver); + $this->assertInstanceOf(\Bernard\Driver::class, $this->driver); } public function testItCountsNumberOfMessagesInQueue() @@ -65,7 +72,7 @@ public function testItListQueues() public function testAcknowledgeMessage() { $this->pheanstalk->expects($this->once())->method('delete') - ->with($this->isInstanceOf('Pheanstalk\Job')); + ->with($this->isInstanceOf(Job::class)); $this->driver->acknowledgeMessage('my-queue', new Job(1, null)); } diff --git a/tests/Driver/PhpRedisDriverTest.php b/tests/Driver/PhpRedis/DriverTest.php similarity index 92% rename from tests/Driver/PhpRedisDriverTest.php rename to tests/Driver/PhpRedis/DriverTest.php index d0c7efc4..28659095 100644 --- a/tests/Driver/PhpRedisDriverTest.php +++ b/tests/Driver/PhpRedis/DriverTest.php @@ -1,10 +1,10 @@ getMock(); - $this->connection = new PhpRedisDriver($this->redis); + $this->connection = new Driver($this->redis); } public function testItImplementsDriverInterface() { - $this->assertInstanceOf('Bernard\Driver', $this->connection); + $this->assertInstanceOf(\Bernard\Driver::class, $this->connection); } public function testItCountsNumberOfMessagesInQueue() diff --git a/tests/Driver/PredisDriverTest.php b/tests/Driver/Predis/DriverTest.php similarity index 78% rename from tests/Driver/PredisDriverTest.php rename to tests/Driver/Predis/DriverTest.php index b8330edf..523b0201 100644 --- a/tests/Driver/PredisDriverTest.php +++ b/tests/Driver/Predis/DriverTest.php @@ -1,16 +1,17 @@ redis = $this->getMockBuilder('Predis\Client')->setMethods(array( + $this->redis = $this->getMockBuilder(Client::class)->setMethods(array( 'lLen', 'sMembers', 'lRange', @@ -23,7 +24,7 @@ public function setUp() 'sRem', ))->getMock(); - $this->connection = new PredisDriver($this->redis); + $this->connection = new Driver($this->redis); } public function testItPopMessages() diff --git a/tests/Driver/SqsDriverTest.php b/tests/Driver/Sqs/DriverTest.php similarity index 93% rename from tests/Driver/SqsDriverTest.php rename to tests/Driver/Sqs/DriverTest.php index 29b665a8..0b68feba 100644 --- a/tests/Driver/SqsDriverTest.php +++ b/tests/Driver/Sqs/DriverTest.php @@ -1,21 +1,28 @@ sqs = $this->getMockBuilder('Aws\Sqs\SqsClient') + $this->sqs = $this->getMockBuilder(SqsClient::class) ->disableOriginalConstructor() ->setMethods(array( 'createQueue', @@ -29,12 +36,12 @@ public function setUp() )) ->getMock(); - $this->driver = new SqsDriver($this->sqs, ['send-newsletter' => 'url']); + $this->driver = new Driver($this->sqs, ['send-newsletter' => 'url']); } public function testItExposesInfo() { - $driver = new SqsDriver($this->sqs, [], 10); + $driver = new Driver($this->sqs, [], 10); $this->assertEquals(['prefetch' => 10], $driver->info()); $this->assertEquals(['prefetch' => 2], $this->driver->info()); @@ -42,7 +49,7 @@ public function testItExposesInfo() public function testItImplementsDriverInterface() { - $this->assertInstanceOf('Bernard\Driver\AbstractPrefetchDriver', $this->driver); + $this->assertInstanceOf(AbstractPrefetchDriver::class, $this->driver); } public function testItCreatesQueue() @@ -127,7 +134,7 @@ public function testUnresolveableQueueNameThrowsException() public function testItGetsAllQueues() { - $driver = new SqsDriver($this->sqs, [ + $driver = new Driver($this->sqs, [ 'import-users' => 'alreadyknowurl/import_users_prod' ]); @@ -195,7 +202,7 @@ public function testItPushesMessagesToFifoQueue() ->with($this->equalTo([ 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX. '/'. self::DUMMY_FIFO_QUEUE_NAME, 'MessageBody' => $message, - 'MessageGroupId' => \Bernard\Driver\SqsDriver::class . '::pushMessage', + 'MessageGroupId' => \Bernard\Driver\Sqs\Driver::class . '::pushMessage', 'MessageDeduplicationId' => md5($message), ])); diff --git a/tests/Fixtures/PushTask.php b/tests/Fixtures/PushTask.php index a8e0c190..877878e4 100644 --- a/tests/Fixtures/PushTask.php +++ b/tests/Fixtures/PushTask.php @@ -8,7 +8,7 @@ */ class PushTask { - static $messages = array(); + public static $messages = array(); protected $url_path; protected $query_data; From 37a182a0c02c7c0d4b877d1262776688496e149a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Wed, 14 Feb 2018 01:59:12 +0100 Subject: [PATCH 009/108] Massive coding style fixes --- .gitignore | 13 ++-- .php_cs.dist | 15 +++++ example/bootstrap.php | 51 ++++++++------- example/doctrine.php | 9 +-- example/file.php | 4 +- example/ironmq.php | 9 +-- example/pheanstalk.php | 3 +- example/phpredis.php | 5 +- example/predis.php | 7 ++- example/sqs.php | 11 ++-- src/BernardEvents.php | 2 +- src/Command/ConsumeCommand.php | 3 - src/Command/ProduceCommand.php | 5 +- src/Consumer.php | 20 +++--- src/Driver.php | 3 - src/Driver/AbstractPrefetchDriver.php | 4 +- src/Driver/Amqp/Driver.php | 2 +- src/Driver/AppEngine/Driver.php | 4 +- .../Doctrine/Command/AbstractCommand.php | 21 +++---- src/Driver/Doctrine/Command/CreateCommand.php | 7 +-- src/Driver/Doctrine/Command/DropCommand.php | 7 +-- src/Driver/Doctrine/Command/UpdateCommand.php | 7 +-- src/Driver/Doctrine/ConnectionListener.php | 9 ++- src/Driver/Doctrine/Driver.php | 10 ++- src/Driver/Doctrine/MessagesSchema.php | 3 - src/Driver/FlatFile/Driver.php | 12 ++-- src/Driver/IronMQ/Driver.php | 14 ++--- src/Driver/MongoDB/Driver.php | 4 +- src/Driver/Pheanstalk/Driver.php | 6 +- src/Driver/PhpRedis/Driver.php | 10 ++- src/Driver/Predis/Driver.php | 3 - src/Driver/PrefetchMessageCache.php | 3 - src/Driver/Sqs/Driver.php | 24 ++++--- src/Envelope.php | 2 - src/Event/EnvelopeEvent.php | 3 - src/Event/PingEvent.php | 3 - src/Event/RejectEnvelopeEvent.php | 3 - src/EventListener/ErrorLogSubscriber.php | 8 +-- src/EventListener/FailureSubscriber.php | 5 +- src/EventListener/LoggerSubscriber.php | 3 - src/Exception/Exception.php | 3 +- src/Exception/InvalidArgumentException.php | 3 - src/Exception/InvalidOperationException.php | 3 - src/Exception/NotImplementedException.php | 3 +- src/Exception/QueueNotFoundException.php | 3 +- src/Exception/ReceiverNotFoundException.php | 2 - src/Exception/ServiceUnavailableException.php | 3 +- src/Message.php | 3 - src/Message/AbstractMessage.php | 3 - src/Message/DefaultMessage.php | 1 - src/Message/PlainMessage.php | 2 - src/Normalizer/EnvelopeNormalizer.php | 3 - src/Normalizer/PlainMessageNormalizer.php | 3 - src/Producer.php | 3 - src/Queue.php | 5 +- src/Queue/AbstractQueue.php | 3 - src/Queue/InMemoryQueue.php | 6 +- src/Queue/PersistentQueue.php | 9 +-- src/Queue/RoundRobinQueue.php | 11 ++-- src/QueueFactory.php | 2 - src/QueueFactory/InMemoryFactory.php | 4 +- src/QueueFactory/PersistentFactory.php | 2 - src/Router.php | 3 - src/Router/ClassNameRouter.php | 3 - src/Router/ContainerAwareRouter.php | 3 - src/Router/LeagueContainerAwareRouter.php | 5 +- src/Router/PimpleAwareRouter.php | 3 - src/Router/SimpleRouter.php | 4 +- src/Serializer.php | 3 - src/Util.php | 3 - tests/Command/ConsumeCommandTest.php | 18 +++--- tests/Command/ProduceCommandTest.php | 24 +++---- tests/ConsumerTest.php | 30 ++++----- tests/Driver/Amqp/DriverTest.php | 12 ++-- tests/Driver/AppEngine/DriverTest.php | 18 +++--- tests/Driver/Doctrine/AbstractDriverTest.php | 13 ++-- .../Doctrine/Command/BaseCommandTest.php | 2 +- .../Doctrine/ConnectionListenerTest.php | 2 - tests/Driver/Doctrine/MySQLDriverTest.php | 22 +++---- .../Driver/Doctrine/PostgreSQLDriverTest.php | 18 +++--- tests/Driver/Doctrine/SQLiteDriverTest.php | 16 ++--- tests/Driver/FlatFile/DriverTest.php | 4 +- tests/Driver/InMemory/DriverTest.php | 34 +++++----- tests/Driver/Interop/DriverTest.php | 2 +- tests/Driver/IronMQ/DriverTest.php | 60 +++++++++--------- tests/Driver/MongoDB/DriverFunctionalTest.php | 26 ++++---- tests/Driver/MongoDB/DriverTest.php | 54 ++++++++-------- tests/Driver/Pheanstalk/DriverTest.php | 22 +++---- tests/Driver/PhpRedis/DriverTest.php | 29 +++++---- tests/Driver/Predis/DriverTest.php | 12 ++-- tests/Driver/PrefetchMessageCacheTest.php | 6 +- tests/Driver/Sqs/DriverTest.php | 63 +++++++++---------- .../EventListener/ErrorLogSubscriberTest.php | 3 +- tests/EventListener/FailureSubscriberTest.php | 3 +- tests/Exception/ExceptionTest.php | 5 +- tests/Fixtures/PushTask.php | 4 +- tests/Fixtures/SendNewsletterMessage.php | 4 +- tests/Fixtures/Service.php | 2 +- tests/Message/AbstractMessageTest.php | 6 +- tests/Message/PlainMessageTest.php | 9 ++- tests/ProducerTest.php | 8 +-- tests/Queue/AbstractQueueTest.php | 26 ++++---- tests/Queue/InMemoryQueueTest.php | 8 +-- tests/Queue/PersistentQueueTest.php | 18 +++--- tests/Queue/RoundRobinQueueTest.php | 2 +- tests/QueueFactory/PersistentFactoryTest.php | 4 +- tests/Router/ContainerAwareRouterTest.php | 8 +-- .../Router/LeagueContainerAwareRouterTest.php | 4 +- tests/Router/PimpleAwareRouterTest.php | 4 +- tests/Router/SimpleRouterTest.php | 16 ++--- 110 files changed, 475 insertions(+), 590 deletions(-) create mode 100644 .php_cs.dist diff --git a/.gitignore b/.gitignore index 5e3bf393..019557db 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,8 @@ -composer.lock -vendor -phpunit.xml -coverage -_build +/build/ +/_build/ +/composer.lock +/phpspec.yml +/phpunit.xml +/.php_cs +/.php_cs.cache +/vendor/ diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 00000000..44307173 --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,15 @@ +exclude('spec') + ->in(__DIR__) +; + +return PhpCsFixer\Config::create() + ->setRules([ + '@Symfony' => true, + 'array_syntax' => ['syntax' => 'short'], + 'yoda_style' => false, + ]) + ->setFinder($finder) + ; diff --git a/example/bootstrap.php b/example/bootstrap.php index 170060bf..10a89aea 100644 --- a/example/bootstrap.php +++ b/example/bootstrap.php @@ -9,71 +9,80 @@ use Bernard\Serializer; use Symfony\Component\EventDispatcher\EventDispatcher; -/** +/* * This file contains helper methods for the examples. See example/$driver.php * for how to initiate the driver. Also the helper methods can be used as * guidance if you are using Bernard outside a framework or you are developing * a plugin to a framework. */ -if (file_exists($autoloadFile = __DIR__ . '/../vendor/autoload.php') || file_exists($autoloadFile = __DIR__ . '/../../../autoload.php')) { +if (file_exists($autoloadFile = __DIR__.'/../vendor/autoload.php') || file_exists($autoloadFile = __DIR__.'/../../../autoload.php')) { require $autoloadFile; } -require __DIR__ . '/EchoTimeService.php'; +require __DIR__.'/EchoTimeService.php'; ini_set('display_errors', 1); error_reporting(E_ALL); -function get_serializer() { - return new Serializer; +function get_serializer() +{ + return new Serializer(); } -function get_event_dispatcher() { - $dispatcher = new EventDispatcher; - $dispatcher->addSubscriber(new EventListener\ErrorLogSubscriber); +function get_event_dispatcher() +{ + $dispatcher = new EventDispatcher(); + $dispatcher->addSubscriber(new EventListener\ErrorLogSubscriber()); $dispatcher->addSubscriber(new EventListener\FailureSubscriber(get_producer())); return $dispatcher; } -function get_queue_factory() { +function get_queue_factory() +{ return new PersistentFactory(get_driver(), get_serializer()); } -function get_producer() { +function get_producer() +{ return new Producer(get_queue_factory(), get_event_dispatcher()); } -function get_receivers() { - return new SimpleRouter(array( - 'EchoTime' => new EchoTimeService, - )); +function get_receivers() +{ + return new SimpleRouter([ + 'EchoTime' => new EchoTimeService(), + ]); } -function get_consumer() { +function get_consumer() +{ return new Consumer(get_receivers(), get_event_dispatcher()); } -function produce() { +function produce() +{ $producer = get_producer(); while (true) { - $producer->produce(new Message\PlainMessage('EchoTime', array( + $producer->produce(new Message\PlainMessage('EchoTime', [ 'time' => time(), - ))); + ])); usleep(rand(100, 1000)); } } -function consume() { - $queues = get_queue_factory(); +function consume() +{ + $queues = get_queue_factory(); $consumer = get_consumer(); $consumer->consume($queues->create('echo-time')); } -function main() { +function main() +{ if (!isset($_SERVER['argv'][1])) { die('You must provide an argument of either "consume" or "produce"'); } diff --git a/example/doctrine.php b/example/doctrine.php index a28f0e10..99a81460 100644 --- a/example/doctrine.php +++ b/example/doctrine.php @@ -7,14 +7,15 @@ * Must be defined before including bootstrap.php * as this is the only custom part in the example. */ -function get_driver() { - $connection = DriverManager::getConnection(array( +function get_driver() +{ + $connection = DriverManager::getConnection([ 'dbname' => 'bernard', 'user' => 'root', 'password' => null, 'host' => 'localhost', 'driver' => 'pdo_mysql', - )); + ]); $doctrineDriver = new Driver($connection); @@ -26,7 +27,7 @@ function get_driver() { \Bernard\Driver\Doctrine\MessagesSchema::create($schema); - array_map(array($connection, 'executeQuery'), $schema->toSql($connection->getDatabasePlatform())); + array_map([$connection, 'executeQuery'], $schema->toSql($connection->getDatabasePlatform())); } return $doctrineDriver; diff --git a/example/file.php b/example/file.php index 6d721cf6..f83ab828 100644 --- a/example/file.php +++ b/example/file.php @@ -6,8 +6,8 @@ * Must be defined before including bootstrap.php * as this is the only custom part in the example. */ - -function get_driver() { +function get_driver() +{ $baseDir = sys_get_temp_dir().DIRECTORY_SEPARATOR.'bernard'; if (!is_dir($baseDir)) { diff --git a/example/ironmq.php b/example/ironmq.php index f56b6897..014ad327 100644 --- a/example/ironmq.php +++ b/example/ironmq.php @@ -7,11 +7,12 @@ * Must be defined before including bootstrap.php * as this is the only custom part in the example. */ -function get_driver() { - $ironmq = new IronMQ(array( - 'token' => getenv('IRONMQ_TOKEN'), +function get_driver() +{ + $ironmq = new IronMQ([ + 'token' => getenv('IRONMQ_TOKEN'), 'project_id' => getenv('IRONMQ_PROJECT_ID'), - )); + ]); return new Driver($ironmq); } diff --git a/example/pheanstalk.php b/example/pheanstalk.php index aabe72ca..1a3f0ef7 100644 --- a/example/pheanstalk.php +++ b/example/pheanstalk.php @@ -7,7 +7,8 @@ * Must be defined before including bootstrap.php * as this is the only custom part in the example. */ -function get_driver() { +function get_driver() +{ $pheanstalk = new Pheanstalk('localhost'); return new Driver($pheanstalk); diff --git a/example/phpredis.php b/example/phpredis.php index 5e21e4b1..4d467774 100644 --- a/example/phpredis.php +++ b/example/phpredis.php @@ -6,8 +6,9 @@ * Must be defined before including bootstrap.php * as this is the only custom part in the example. */ -function get_driver() { - $redis = new Redis; +function get_driver() +{ + $redis = new Redis(); $redis->connect('localhost'); $redis->setOption(Redis::OPT_PREFIX, 'bernard:'); diff --git a/example/predis.php b/example/predis.php index 169201ad..e433c39d 100644 --- a/example/predis.php +++ b/example/predis.php @@ -7,10 +7,11 @@ * Must be defined before including bootstrap.php * as this is the only custom part in the example. */ -function get_driver() { - return new Driver(new Client(null, array( +function get_driver() +{ + return new Driver(new Client(null, [ 'prefix' => 'bernard:', - ))); + ])); } require 'bootstrap.php'; diff --git a/example/sqs.php b/example/sqs.php index 3f31d2d4..6f64c694 100644 --- a/example/sqs.php +++ b/example/sqs.php @@ -7,12 +7,13 @@ * Must be defined before including bootstrap.php * as this is the only custom part in the example. */ -function get_driver() { - $sqs = SqsClient::factory(array( - 'key' => getenv('ACCESS_KEY'), +function get_driver() +{ + $sqs = SqsClient::factory([ + 'key' => getenv('ACCESS_KEY'), 'secret' => getenv('SECRET_KEY'), - 'region' => getenv('SQS_REGION') - )); + 'region' => getenv('SQS_REGION'), + ]); return new Driver($sqs); } diff --git a/src/BernardEvents.php b/src/BernardEvents.php index bfb82c53..0233b1a4 100644 --- a/src/BernardEvents.php +++ b/src/BernardEvents.php @@ -3,7 +3,7 @@ namespace Bernard; /** - * Contains all events dispatched by bernard + * Contains all events dispatched by bernard. */ final class BernardEvents { diff --git a/src/Command/ConsumeCommand.php b/src/Command/ConsumeCommand.php index 006269fd..60046eeb 100644 --- a/src/Command/ConsumeCommand.php +++ b/src/Command/ConsumeCommand.php @@ -11,9 +11,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -/** - * @package Bernard - */ class ConsumeCommand extends \Symfony\Component\Console\Command\Command { protected $consumer; diff --git a/src/Command/ProduceCommand.php b/src/Command/ProduceCommand.php index ffc5503a..be308b15 100644 --- a/src/Command/ProduceCommand.php +++ b/src/Command/ProduceCommand.php @@ -9,9 +9,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -/** - * @package Bernard - */ class ProduceCommand extends \Symfony\Component\Console\Command\Command { protected $producer; @@ -51,7 +48,7 @@ public function execute(InputInterface $input, OutputInterface $output) $message = json_decode($input->getArgument('message'), true); if (json_last_error()) { - throw new \RuntimeException('Could not decode invalid JSON [' . json_last_error() . ']'); + throw new \RuntimeException('Could not decode invalid JSON ['.json_last_error().']'); } } diff --git a/src/Consumer.php b/src/Consumer.php index f6cbe54c..b83e5853 100644 --- a/src/Consumer.php +++ b/src/Consumer.php @@ -7,9 +7,6 @@ use Bernard\Event\PingEvent; use Bernard\Event\RejectEnvelopeEvent; -/** - * @package Consumer - */ class Consumer { protected $router; @@ -35,14 +32,14 @@ public function __construct(Router $router, EventDispatcherInterface $dispatcher } /** - * Starts an infinite loop calling Consumer::tick(); + * Starts an infinite loop calling Consumer::tick();. * * @param Queue $queue * @param array $options */ public function consume(Queue $queue, array $options = []) { - declare (ticks = 1); + declare(ticks=1); $this->bind(); @@ -88,11 +85,11 @@ public function tick(Queue $queue, array $options = []) return true; } - return (boolean) --$this->options['max-messages']; + return (bool) --$this->options['max-messages']; } /** - * Mark Consumer as shutdown + * Mark Consumer as shutdown. */ public function shutdown() { @@ -100,7 +97,7 @@ public function shutdown() } /** - * Pause consuming + * Pause consuming. */ public function pause() { @@ -108,7 +105,7 @@ public function pause() } /** - * Resume consuming + * Resume consuming. */ public function resume() { @@ -146,8 +143,6 @@ public function invoke(Envelope $envelope, Queue $queue) /** * @param array $options - * - * @return void */ protected function configure(array $options) { @@ -171,7 +166,7 @@ protected function bind() { if (function_exists('pcntl_signal')) { pcntl_signal(SIGTERM, [$this, 'shutdown']); - pcntl_signal(SIGINT, [$this, 'shutdown']); + pcntl_signal(SIGINT, [$this, 'shutdown']); pcntl_signal(SIGQUIT, [$this, 'shutdown']); pcntl_signal(SIGUSR2, [$this, 'pause']); pcntl_signal(SIGCONT, [$this, 'resume']); @@ -180,7 +175,6 @@ protected function bind() /** * @param \Throwable|\Exception $exception note that the type-hint is missing due to PHP 5.x compat - * * @param Envelope $envelope * @param Queue $queue * diff --git a/src/Driver.php b/src/Driver.php index 5ba15431..b98a0c52 100644 --- a/src/Driver.php +++ b/src/Driver.php @@ -2,9 +2,6 @@ namespace Bernard; -/** - * @package Bernard - */ interface Driver { /** diff --git a/src/Driver/AbstractPrefetchDriver.php b/src/Driver/AbstractPrefetchDriver.php index 1fde43e4..ec97fd8a 100644 --- a/src/Driver/AbstractPrefetchDriver.php +++ b/src/Driver/AbstractPrefetchDriver.php @@ -5,8 +5,6 @@ /** * For some drivers it gives a performance boost not to query the backend * all the time. This is mostly for SQS and IronMQ. - * - * @package Bernard */ abstract class AbstractPrefetchDriver implements \Bernard\Driver { @@ -18,7 +16,7 @@ abstract class AbstractPrefetchDriver implements \Bernard\Driver */ public function __construct($prefetch = null) { - $this->prefetch = $prefetch ? (integer) $prefetch : 2; + $this->prefetch = $prefetch ? (int) $prefetch : 2; $this->cache = new PrefetchMessageCache(); } } diff --git a/src/Driver/Amqp/Driver.php b/src/Driver/Amqp/Driver.php index 2ad1e01b..4926a7c6 100644 --- a/src/Driver/Amqp/Driver.php +++ b/src/Driver/Amqp/Driver.php @@ -71,7 +71,7 @@ public function createQueue($queueName) */ public function countMessages($queueName) { - list(,$messageCount) = $this->getChannel()->queue_declare($queueName, true); + list(, $messageCount) = $this->getChannel()->queue_declare($queueName, true); return $messageCount; } diff --git a/src/Driver/AppEngine/Driver.php b/src/Driver/AppEngine/Driver.php index 291329ca..89fea9dc 100644 --- a/src/Driver/AppEngine/Driver.php +++ b/src/Driver/AppEngine/Driver.php @@ -8,8 +8,6 @@ * Simple driver for google AppEngine. Many features are not supported. * It takes a list of array('name' => 'endpoint') to route messages to the * correct place. - * - * @package Bernard */ final class Driver implements \Bernard\Driver { @@ -102,6 +100,6 @@ private function resolveEndpoint($queueName) return $this->queueMap[$queueName]; } - return '/_ah/queue/' . $queueName; + return '/_ah/queue/'.$queueName; } } diff --git a/src/Driver/Doctrine/Command/AbstractCommand.php b/src/Driver/Doctrine/Command/AbstractCommand.php index 75b2e373..e767cf99 100644 --- a/src/Driver/Doctrine/Command/AbstractCommand.php +++ b/src/Driver/Doctrine/Command/AbstractCommand.php @@ -11,18 +11,15 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -/** - * @package Bernard - */ abstract class AbstractCommand extends Command { public function __construct($name) { - parent::__construct('bernard:doctrine:' . $name); + parent::__construct('bernard:doctrine:'.$name); } /** - * {@inheritDoc} + * {@inheritdoc} */ public function configure() { @@ -30,20 +27,21 @@ public function configure() } /** - * {@inheritDoc} + * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { - $schema = new Schema; + $schema = new Schema(); MessagesSchema::create($schema); $sync = $this->getSynchronizer($this->getHelper('connection')->getConnection()); if ($input->getOption('dump-sql')) { - $output->writeln(implode(';' . PHP_EOL, $this->getSql($sync, $schema)) . ';'); + $output->writeln(implode(';'.PHP_EOL, $this->getSql($sync, $schema)).';'); + return; } - $output->writeln('ATTENTION: This operation should not be executed in a production environment.' . PHP_EOL); + $output->writeln('ATTENTION: This operation should not be executed in a production environment.'.PHP_EOL); $output->writeln('Applying database schema changes...'); $this->applySql($sync, $schema); $output->writeln('Schema changes applied successfully!'); @@ -59,14 +57,15 @@ protected function getSynchronizer(Connection $connection) /** * @param \Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer $sync - * @param \Doctrine\DBAL\Schema\Schema $schema + * @param \Doctrine\DBAL\Schema\Schema $schema + * * @return array */ abstract protected function getSql(Synchronizer $sync, Schema $schema); /** * @param \Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer $sync - * @param \Doctrine\DBAL\Schema\Schema $schema + * @param \Doctrine\DBAL\Schema\Schema $schema */ abstract protected function applySql(Synchronizer $sync, Schema $schema); } diff --git a/src/Driver/Doctrine/Command/CreateCommand.php b/src/Driver/Doctrine/Command/CreateCommand.php index 99c76c28..abd571a3 100644 --- a/src/Driver/Doctrine/Command/CreateCommand.php +++ b/src/Driver/Doctrine/Command/CreateCommand.php @@ -5,9 +5,6 @@ use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer as Synchronizer; -/** - * @package Bernard - */ class CreateCommand extends AbstractCommand { public function __construct() @@ -16,7 +13,7 @@ public function __construct() } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function getSql(Synchronizer $sync, Schema $schema) { @@ -24,7 +21,7 @@ protected function getSql(Synchronizer $sync, Schema $schema) } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function applySql(Synchronizer $sync, Schema $schema) { diff --git a/src/Driver/Doctrine/Command/DropCommand.php b/src/Driver/Doctrine/Command/DropCommand.php index c7e29f0d..d9cbaac9 100644 --- a/src/Driver/Doctrine/Command/DropCommand.php +++ b/src/Driver/Doctrine/Command/DropCommand.php @@ -5,9 +5,6 @@ use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer as Synchronizer; -/** - * @package Bernard - */ class DropCommand extends AbstractCommand { public function __construct() @@ -16,7 +13,7 @@ public function __construct() } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function getSql(Synchronizer $sync, Schema $schema) { @@ -24,7 +21,7 @@ protected function getSql(Synchronizer $sync, Schema $schema) } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function applySql(Synchronizer $sync, Schema $schema) { diff --git a/src/Driver/Doctrine/Command/UpdateCommand.php b/src/Driver/Doctrine/Command/UpdateCommand.php index d35060ea..72e09465 100644 --- a/src/Driver/Doctrine/Command/UpdateCommand.php +++ b/src/Driver/Doctrine/Command/UpdateCommand.php @@ -5,9 +5,6 @@ use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer as Synchronizer; -/** - * @package Bernard - */ class UpdateCommand extends AbstractCommand { public function __construct() @@ -16,7 +13,7 @@ public function __construct() } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function getSql(Synchronizer $sync, Schema $schema) { @@ -24,7 +21,7 @@ protected function getSql(Synchronizer $sync, Schema $schema) } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function applySql(Synchronizer $sync, Schema $schema) { diff --git a/src/Driver/Doctrine/ConnectionListener.php b/src/Driver/Doctrine/ConnectionListener.php index 5db1a02e..5d8c0e38 100644 --- a/src/Driver/Doctrine/ConnectionListener.php +++ b/src/Driver/Doctrine/ConnectionListener.php @@ -6,10 +6,9 @@ use Doctrine\DBAL\DBALException; /** - * Inspired by Swarrots ConnectionProcessor (https://github.com/swarrot/swarrot/blob/master/src/Swarrot/Processor/Doctrine/ConnectionProcessor.php) + * Inspired by Swarrots ConnectionProcessor (https://github.com/swarrot/swarrot/blob/master/src/Swarrot/Processor/Doctrine/ConnectionProcessor.php). * * @author Markus Bachmann - * @package Bernard */ class ConnectionListener implements EventSubscriberInterface { @@ -20,15 +19,15 @@ class ConnectionListener implements EventSubscriberInterface public static function getSubscribedEvents() { - return array( + return [ 'bernard.invoke' => 'onPing', - ); + ]; } public function __construct($connections) { if (!is_array($connections)) { - $connections = array($connections); + $connections = [$connections]; } $this->connections = $connections; diff --git a/src/Driver/Doctrine/Driver.php b/src/Driver/Doctrine/Driver.php index f6fb27b8..dd1ec374 100644 --- a/src/Driver/Doctrine/Driver.php +++ b/src/Driver/Doctrine/Driver.php @@ -5,9 +5,7 @@ use Doctrine\DBAL\Connection; /** - * Driver supporting Doctrine DBAL - * - * @package Bernard + * Driver supporting Doctrine DBAL. */ final class Driver implements \Bernard\Driver { @@ -52,7 +50,7 @@ public function countMessages($queueName) { $query = 'SELECT COUNT(id) FROM bernard_messages WHERE queue = :queue AND visible = :visible'; - return (integer) $this->connection->fetchColumn($query, [ + return (int) $this->connection->fetchColumn($query, [ 'queue' => $queueName, 'visible' => true, ]); @@ -148,7 +146,7 @@ public function info() } /** - * Execute the actual query and process the response + * Execute the actual query and process the response. * * @param string $queueName * @@ -158,7 +156,7 @@ private function doPopMessage($queueName) { $query = 'SELECT id, message FROM bernard_messages WHERE queue = :queue AND visible = :visible - ORDER BY sentAt LIMIT 1 ' . $this->connection->getDatabasePlatform()->getForUpdateSql(); + ORDER BY sentAt LIMIT 1 '.$this->connection->getDatabasePlatform()->getForUpdateSql(); list($id, $message) = $this->connection->fetchArray($query, [ 'queue' => $queueName, diff --git a/src/Driver/Doctrine/MessagesSchema.php b/src/Driver/Doctrine/MessagesSchema.php index 5e7d6baa..439a35a5 100644 --- a/src/Driver/Doctrine/MessagesSchema.php +++ b/src/Driver/Doctrine/MessagesSchema.php @@ -4,9 +4,6 @@ use Doctrine\DBAL\Schema\Schema; -/** - * @package Bernard - */ class MessagesSchema { /** diff --git a/src/Driver/FlatFile/Driver.php b/src/Driver/FlatFile/Driver.php index dc9737ec..2bdd44d8 100644 --- a/src/Driver/FlatFile/Driver.php +++ b/src/Driver/FlatFile/Driver.php @@ -16,7 +16,7 @@ class Driver implements \Bernard\Driver /** * @param string $baseDirectory The base directory - * @param int $permissions Permissions to create the file with. + * @param int $permissions permissions to create the file with */ public function __construct($baseDirectory, $permissions = 0740) { @@ -83,7 +83,7 @@ public function pushMessage($queueName, $message) $filename = $this->getJobFilename($queueName); file_put_contents($queueDir.DIRECTORY_SEPARATOR.$filename, $message); - chmod($queueDir . DIRECTORY_SEPARATOR . $filename, $this->permissions); + chmod($queueDir.DIRECTORY_SEPARATOR.$filename, $this->permissions); } /** @@ -103,14 +103,14 @@ public function popMessage($queueName, $duration = 5) if ($files) { $id = array_pop($files); if (@rename($queueDir.DIRECTORY_SEPARATOR.$id, $queueDir.DIRECTORY_SEPARATOR.$id.'.proceed')) { - return array(file_get_contents($queueDir.DIRECTORY_SEPARATOR.$id.'.proceed'), $id); + return [file_get_contents($queueDir.DIRECTORY_SEPARATOR.$id.'.proceed'), $id]; } } usleep(1000); } - return array(null, null); + return [null, null]; } /** @@ -187,7 +187,7 @@ public function info() */ private function getQueueDirectory($queueName) { - return $this->baseDirectory.DIRECTORY_SEPARATOR.str_replace(array('\\', '.'), '-', $queueName); + return $this->baseDirectory.DIRECTORY_SEPARATOR.str_replace(['\\', '.'], '-', $queueName); } /** @@ -212,7 +212,7 @@ private function getJobFilename($queueName) $meta = unserialize($file->fgets()); $id = isset($meta[$queueName]) ? $meta[$queueName] : 0; - $id++; + ++$id; $filename = sprintf('%d.job', $id); $meta[$queueName] = $id; diff --git a/src/Driver/IronMQ/Driver.php b/src/Driver/IronMQ/Driver.php index 617ddb92..a86312e9 100644 --- a/src/Driver/IronMQ/Driver.php +++ b/src/Driver/IronMQ/Driver.php @@ -7,9 +7,7 @@ /** * Implements a Driver for use with Iron MQ: - * https://github.com/iron-io/iron_mq_php - * - * @package Bernard + * https://github.com/iron-io/iron_mq_php. */ final class Driver extends AbstractPrefetchDriver { @@ -31,7 +29,7 @@ public function __construct(IronMQ $ironmq, $prefetch = null) */ public function listQueues() { - $queueNames = array(); + $queueNames = []; $page = 0; while ($queues = $this->ironmq->getQueues($page, 100)) { @@ -42,7 +40,7 @@ public function listQueues() break; } - $page++; + ++$page; } return $queueNames; @@ -87,11 +85,11 @@ public function popMessage($queueName, $duration = 5) $messages = $this->ironmq->getMessages($queueName, $this->prefetch, $timeout, $duration); if (!$messages) { - return array(null, null); + return [null, null]; } foreach ($messages as $message) { - $this->cache->push($queueName, array($message->body, $message->id)); + $this->cache->push($queueName, [$message->body, $message->id]); } return $this->cache->pop($queueName); @@ -138,7 +136,7 @@ public function info() } /** - * The missing array_pluck but for objects array + * The missing array_pluck but for objects array. * * @param array $objects * @param string $property diff --git a/src/Driver/MongoDB/Driver.php b/src/Driver/MongoDB/Driver.php index 25cbd6d5..80406efb 100644 --- a/src/Driver/MongoDB/Driver.php +++ b/src/Driver/MongoDB/Driver.php @@ -7,9 +7,7 @@ use MongoId; /** - * Driver supporting MongoDB - * - * @package Bernard + * Driver supporting MongoDB. */ final class Driver implements \Bernard\Driver { diff --git a/src/Driver/Pheanstalk/Driver.php b/src/Driver/Pheanstalk/Driver.php index 3dac8f49..a91486e8 100644 --- a/src/Driver/Pheanstalk/Driver.php +++ b/src/Driver/Pheanstalk/Driver.php @@ -5,9 +5,7 @@ use Pheanstalk\PheanstalkInterface; /** - * Implements a Driver for use with https://github.com/pda/pheanstalk - * - * @package Bernard + * Implements a Driver for use with https://github.com/pda/pheanstalk. */ final class Driver implements \Bernard\Driver { @@ -63,7 +61,7 @@ public function popMessage($queueName, $duration = 5) return [$job->getData(), $job]; } - return array(null, null); + return [null, null]; } /** diff --git a/src/Driver/PhpRedis/Driver.php b/src/Driver/PhpRedis/Driver.php index 83d8ab3f..9234feca 100644 --- a/src/Driver/PhpRedis/Driver.php +++ b/src/Driver/PhpRedis/Driver.php @@ -5,14 +5,12 @@ use Redis; /** - * Implements a Driver for use with https://github.com/nicolasff/phpredis - * - * @package Bernard + * Implements a Driver for use with https://github.com/nicolasff/phpredis. */ class Driver implements \Bernard\Driver { const QUEUE_PREFIX = 'queue:'; - + protected $redis; /** @@ -44,7 +42,7 @@ public function createQueue($queueName) */ public function countMessages($queueName) { - return $this->redis->lLen(self::QUEUE_PREFIX . $queueName); + return $this->redis->lLen(self::QUEUE_PREFIX.$queueName); } /** @@ -116,6 +114,6 @@ public function info() */ protected function resolveKey($queueName) { - return self::QUEUE_PREFIX . $queueName; + return self::QUEUE_PREFIX.$queueName; } } diff --git a/src/Driver/Predis/Driver.php b/src/Driver/Predis/Driver.php index d820fb8b..dc2afead 100644 --- a/src/Driver/Predis/Driver.php +++ b/src/Driver/Predis/Driver.php @@ -4,9 +4,6 @@ use Predis\ClientInterface; -/** - * @package Bernard - */ final class Driver extends \Bernard\Driver\PhpRedis\Driver { /** diff --git a/src/Driver/PrefetchMessageCache.php b/src/Driver/PrefetchMessageCache.php index 91b07662..fa2d6c69 100644 --- a/src/Driver/PrefetchMessageCache.php +++ b/src/Driver/PrefetchMessageCache.php @@ -2,9 +2,6 @@ namespace Bernard\Driver; -/** - * @package Bernard - */ class PrefetchMessageCache { protected $caches = []; diff --git a/src/Driver/Sqs/Driver.php b/src/Driver/Sqs/Driver.php index 35e11023..a09ff6de 100644 --- a/src/Driver/Sqs/Driver.php +++ b/src/Driver/Sqs/Driver.php @@ -7,10 +7,9 @@ use Bernard\Driver\AbstractPrefetchDriver; /** - * Implements a Driver for use with AWS SQS client API: - * @link http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html + * Implements a Driver for use with AWS SQS client API:. * - * @package Bernard + * @see http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html */ final class Driver extends AbstractPrefetchDriver { @@ -59,15 +58,13 @@ public function listQueues() /** * {@inheritdoc} * - * @link http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#createqueue - * - * @return void + * @see http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#createqueue * * @throws SqsException */ public function createQueue($queueName) { - if($this->queueExists($queueName)){ + if ($this->queueExists($queueName)) { return; } @@ -75,7 +72,7 @@ public function createQueue($queueName) 'QueueName' => $queueName, ]; - if($this->isFifoQueue($queueName)) { + if ($this->isFifoQueue($queueName)) { $parameters['Attributes'] = [ 'FifoQueue' => 'true', ]; @@ -97,6 +94,7 @@ private function queueExists($queueName) { try { $this->resolveUrl($queueName); + return true; } catch (\InvalidArgumentException $exception) { return false; @@ -134,7 +132,7 @@ private function endsWith($haystack, $needle) return true; } - return (substr($haystack, -$length) === $needle); + return substr($haystack, -$length) === $needle; } /** @@ -150,7 +148,7 @@ public function countMessages($queueName) ]); if (isset($result['Attributes']['ApproximateNumberOfMessages'])) { - return (int)$result['Attributes']['ApproximateNumberOfMessages']; + return (int) $result['Attributes']['ApproximateNumberOfMessages']; } return 0; @@ -168,7 +166,7 @@ public function pushMessage($queueName, $message) 'MessageBody' => $message, ]; - if($this->isFifoQueue($queueName)){ + if ($this->isFifoQueue($queueName)) { $parameters['MessageGroupId'] = __METHOD__; $parameters['MessageDeduplicationId'] = md5($message); } @@ -228,7 +226,7 @@ public function peekQueue($queueName, $index = 0, $limit = 20) /** * {@inheritdoc} * - * @link http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#deletequeue + * @see http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#deletequeue */ public function removeQueue($queueName) { @@ -270,6 +268,6 @@ private function resolveUrl($queueName) return $this->queueUrls[$queueName] = $queueUrl; } - throw new \InvalidArgumentException('Queue "' . $queueName .'" cannot be resolved to an url.'); + throw new \InvalidArgumentException('Queue "'.$queueName.'" cannot be resolved to an url.'); } } diff --git a/src/Envelope.php b/src/Envelope.php index 32925c13..b5d6d437 100644 --- a/src/Envelope.php +++ b/src/Envelope.php @@ -5,8 +5,6 @@ /** * Wraps a Message with metadata that can be used for automatic retry * or inspection. - * - * @package Bernard */ class Envelope { diff --git a/src/Event/EnvelopeEvent.php b/src/Event/EnvelopeEvent.php index 3919a78d..060a65fd 100644 --- a/src/Event/EnvelopeEvent.php +++ b/src/Event/EnvelopeEvent.php @@ -5,9 +5,6 @@ use Bernard\Envelope; use Bernard\Queue; -/** - * @package Bernard - */ class EnvelopeEvent extends \Symfony\Component\EventDispatcher\Event { protected $envelope; diff --git a/src/Event/PingEvent.php b/src/Event/PingEvent.php index 63d6c299..77706d93 100644 --- a/src/Event/PingEvent.php +++ b/src/Event/PingEvent.php @@ -5,9 +5,6 @@ use Bernard\Queue; use Symfony\Component\EventDispatcher\Event; -/** - * @package Bernard - */ class PingEvent extends Event { protected $queue; diff --git a/src/Event/RejectEnvelopeEvent.php b/src/Event/RejectEnvelopeEvent.php index 949a83b0..da6a7d09 100644 --- a/src/Event/RejectEnvelopeEvent.php +++ b/src/Event/RejectEnvelopeEvent.php @@ -5,9 +5,6 @@ use Bernard\Envelope; use Bernard\Queue; -/** - * @package Bernard - */ class RejectEnvelopeEvent extends EnvelopeEvent { protected $exception; diff --git a/src/EventListener/ErrorLogSubscriber.php b/src/EventListener/ErrorLogSubscriber.php index a14e7ff7..e83736f8 100644 --- a/src/EventListener/ErrorLogSubscriber.php +++ b/src/EventListener/ErrorLogSubscriber.php @@ -8,9 +8,6 @@ use Exception; use Throwable; -/** - * @package Bernard - */ class ErrorLogSubscriber implements EventSubscriberInterface { /** @@ -23,7 +20,7 @@ public function onReject(RejectEnvelopeEvent $event) /** * @param Envelope $envelope - * @param mixed $exception + * @param mixed $exception * * @return string */ @@ -41,8 +38,9 @@ protected function format(Envelope $envelope, $exception) $replacements = [ '{type}' => is_object($exception) ? get_class($exception) : gettype($exception), - '{envelope}' => $envelope->getName() + '{envelope}' => $envelope->getName(), ]; + return strtr('[bernard] caught unknown error type {type} while processing {envelope}.', $replacements); } diff --git a/src/EventListener/FailureSubscriber.php b/src/EventListener/FailureSubscriber.php index b0c5a320..22740db9 100644 --- a/src/EventListener/FailureSubscriber.php +++ b/src/EventListener/FailureSubscriber.php @@ -6,9 +6,6 @@ use Bernard\Producer; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -/** - * @package Bernard - */ class FailureSubscriber implements EventSubscriberInterface { protected $producer; @@ -16,7 +13,7 @@ class FailureSubscriber implements EventSubscriberInterface /** * @param Producer $producer - * @param string $name + * @param string $name */ public function __construct(Producer $producer, $name = 'failed') { diff --git a/src/EventListener/LoggerSubscriber.php b/src/EventListener/LoggerSubscriber.php index 3155e135..171c3499 100644 --- a/src/EventListener/LoggerSubscriber.php +++ b/src/EventListener/LoggerSubscriber.php @@ -7,9 +7,6 @@ use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -/** - * @package Bernard - */ class LoggerSubscriber implements EventSubscriberInterface { protected $logger; diff --git a/src/Exception/Exception.php b/src/Exception/Exception.php index 4dbe4b26..27ad484f 100644 --- a/src/Exception/Exception.php +++ b/src/Exception/Exception.php @@ -3,8 +3,7 @@ namespace Bernard\Exception; /** - * Interface for exceptions thrown by Bernard - * @package Bernard + * Interface for exceptions thrown by Bernard. */ interface Exception { diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php index b4978515..cb1e81f5 100644 --- a/src/Exception/InvalidArgumentException.php +++ b/src/Exception/InvalidArgumentException.php @@ -2,9 +2,6 @@ namespace Bernard\Exception; -/** - * @package Bernard - */ class InvalidArgumentException extends \InvalidArgumentException implements Exception { } diff --git a/src/Exception/InvalidOperationException.php b/src/Exception/InvalidOperationException.php index cf2f1261..719d13f1 100644 --- a/src/Exception/InvalidOperationException.php +++ b/src/Exception/InvalidOperationException.php @@ -2,9 +2,6 @@ namespace Bernard\Exception; -/** - * @package Bernard - */ class InvalidOperationException extends \Exception implements Exception { } diff --git a/src/Exception/NotImplementedException.php b/src/Exception/NotImplementedException.php index 4ddd07fd..91bb7d3e 100644 --- a/src/Exception/NotImplementedException.php +++ b/src/Exception/NotImplementedException.php @@ -3,8 +3,7 @@ namespace Bernard\Exception; /** - * Thrown when driver does not support requested feature - * @package Bernard + * Thrown when driver does not support requested feature. */ class NotImplementedException extends \BadMethodCallException implements Exception { diff --git a/src/Exception/QueueNotFoundException.php b/src/Exception/QueueNotFoundException.php index d97eedfe..1ae8a74a 100644 --- a/src/Exception/QueueNotFoundException.php +++ b/src/Exception/QueueNotFoundException.php @@ -3,8 +3,7 @@ namespace Bernard\Exception; /** - * Thrown when queue does not exist - * @package Bernard + * Thrown when queue does not exist. */ class QueueNotFoundException extends \RuntimeException implements Exception { diff --git a/src/Exception/ReceiverNotFoundException.php b/src/Exception/ReceiverNotFoundException.php index 38527652..82c202d7 100644 --- a/src/Exception/ReceiverNotFoundException.php +++ b/src/Exception/ReceiverNotFoundException.php @@ -5,8 +5,6 @@ /** * Is thrown when a Router tries to map a Envelope to a receiver and * cannot be done. - * - * @package Bernard */ class ReceiverNotFoundException extends \RuntimeException implements Exception { diff --git a/src/Exception/ServiceUnavailableException.php b/src/Exception/ServiceUnavailableException.php index b0968c55..3cbba674 100644 --- a/src/Exception/ServiceUnavailableException.php +++ b/src/Exception/ServiceUnavailableException.php @@ -3,8 +3,7 @@ namespace Bernard\Exception; /** - * Thrown when driver implementation is unavailable - * @package Bernard + * Thrown when driver implementation is unavailable. */ class ServiceUnavailableException extends \RuntimeException implements Exception { diff --git a/src/Message.php b/src/Message.php index 679ac0dd..c37fa8c8 100644 --- a/src/Message.php +++ b/src/Message.php @@ -2,9 +2,6 @@ namespace Bernard; -/** - * @package Bernard - */ interface Message { /** diff --git a/src/Message/AbstractMessage.php b/src/Message/AbstractMessage.php index 85fd1ecf..fc2dfc65 100644 --- a/src/Message/AbstractMessage.php +++ b/src/Message/AbstractMessage.php @@ -5,9 +5,6 @@ use Bernard\Message; use Bernard\Util; -/** - * @package Bernard - */ abstract class AbstractMessage implements Message { /** diff --git a/src/Message/DefaultMessage.php b/src/Message/DefaultMessage.php index e603591d..d7240199 100644 --- a/src/Message/DefaultMessage.php +++ b/src/Message/DefaultMessage.php @@ -5,7 +5,6 @@ @trigger_error('The '.__NAMESPACE__.'\DefaultMessage class is deprecated. Use '.__NAMESPACE__.'\PlainMessage instead.', E_USER_DEPRECATED); /** - * @package Bernard * @deprecated Use PlainMessage instead */ class DefaultMessage extends PlainMessage diff --git a/src/Message/PlainMessage.php b/src/Message/PlainMessage.php index 2217e42b..d1e4e742 100644 --- a/src/Message/PlainMessage.php +++ b/src/Message/PlainMessage.php @@ -8,8 +8,6 @@ * Simple message that gets you started. It has a name an a array of arguments * It does not enforce any types or properties so be careful on relying them * being there. - * - * @package Bernard */ class PlainMessage extends AbstractMessage implements ArrayAccess { diff --git a/src/Normalizer/EnvelopeNormalizer.php b/src/Normalizer/EnvelopeNormalizer.php index 1e10ec16..cbc3db2e 100644 --- a/src/Normalizer/EnvelopeNormalizer.php +++ b/src/Normalizer/EnvelopeNormalizer.php @@ -7,9 +7,6 @@ use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; -/** - * @package Bernard - */ class EnvelopeNormalizer extends AbstractAggregateNormalizerAware implements NormalizerInterface, DenormalizerInterface { /** diff --git a/src/Normalizer/PlainMessageNormalizer.php b/src/Normalizer/PlainMessageNormalizer.php index 29e55828..e74205ae 100644 --- a/src/Normalizer/PlainMessageNormalizer.php +++ b/src/Normalizer/PlainMessageNormalizer.php @@ -7,9 +7,6 @@ use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; -/** - * @package Bernard - */ class PlainMessageNormalizer implements NormalizerInterface, DenormalizerInterface { /** diff --git a/src/Producer.php b/src/Producer.php index 50e460e2..064671f1 100644 --- a/src/Producer.php +++ b/src/Producer.php @@ -5,9 +5,6 @@ use Bernard\Event\EnvelopeEvent; use Symfony\Component\EventDispatcher\EventDispatcherInterface; -/** - * @package Bernard - */ class Producer { protected $queues; diff --git a/src/Queue.php b/src/Queue.php index 1093087a..0561681f 100644 --- a/src/Queue.php +++ b/src/Queue.php @@ -2,9 +2,6 @@ namespace Bernard; -/** - * @package Bernard - */ interface Queue extends \Countable { /** @@ -40,7 +37,7 @@ public function peek($index = 0, $limit = 20); public function acknowledge(Envelope $envelope); /** - * Return the queue textual representation, normally this will be name (not the internal key) + * Return the queue textual representation, normally this will be name (not the internal key). * * @return string */ diff --git a/src/Queue/AbstractQueue.php b/src/Queue/AbstractQueue.php index c07d0f01..5419638f 100644 --- a/src/Queue/AbstractQueue.php +++ b/src/Queue/AbstractQueue.php @@ -5,9 +5,6 @@ use Bernard\Envelope; use Bernard\Exception\InvalidOperationException; -/** - * @package Bernard - */ abstract class AbstractQueue implements \Bernard\Queue { protected $closed; diff --git a/src/Queue/InMemoryQueue.php b/src/Queue/InMemoryQueue.php index 0dfd0da8..9e57aac1 100644 --- a/src/Queue/InMemoryQueue.php +++ b/src/Queue/InMemoryQueue.php @@ -5,9 +5,7 @@ use Bernard\Envelope; /** - * Wrapper around SplQueue - * - * @package Bernard + * Wrapper around SplQueue. */ class InMemoryQueue extends AbstractQueue { @@ -67,7 +65,7 @@ public function peek($index = 0, $limit = 20) { $this->errorIfClosed(); - $envelopes = array(); + $envelopes = []; $queue = clone $this->queue; $key = 0; diff --git a/src/Queue/PersistentQueue.php b/src/Queue/PersistentQueue.php index 77054a0c..100ee40f 100644 --- a/src/Queue/PersistentQueue.php +++ b/src/Queue/PersistentQueue.php @@ -6,9 +6,6 @@ use Bernard\Envelope; use Bernard\Serializer; -/** - * @package Bernard - */ class PersistentQueue extends AbstractQueue { protected $driver; @@ -32,7 +29,7 @@ public function __construct($name, Driver $driver, Serializer $serializer) } /** - * Register with the driver + * Register with the driver. */ public function register() { @@ -88,7 +85,7 @@ public function acknowledge(Envelope $envelope) /** * {@inheritdoc} * - * @param int $duration Number of seconds to keep polling for messages. + * @param int $duration number of seconds to keep polling for messages */ public function dequeue($duration = 5) { @@ -114,6 +111,6 @@ public function peek($index = 0, $limit = 20) $messages = $this->driver->peekQueue($this->name, $index, $limit); - return array_map(array($this->serializer, 'unserialize'), $messages); + return array_map([$this->serializer, 'unserialize'], $messages); } } diff --git a/src/Queue/RoundRobinQueue.php b/src/Queue/RoundRobinQueue.php index 2e5f7a46..4665524a 100644 --- a/src/Queue/RoundRobinQueue.php +++ b/src/Queue/RoundRobinQueue.php @@ -5,9 +5,6 @@ use Bernard\Envelope; use Bernard\Queue; -/** - * @package Bernard - */ class RoundRobinQueue implements Queue { /** @@ -110,8 +107,8 @@ public function peek($index = 0, $limit = 20) $name = $it->key(); if ($peeked = $queue->peek($indexes[$name], 1)) { if ($shift < $index) { - $shift++; - $indexes[$name]++; + ++$shift; + ++$indexes[$name]; } else { $envelopes[] = array_shift($peeked); } @@ -131,7 +128,7 @@ public function acknowledge(Envelope $envelope) { if (!$this->envelopes->contains($envelope)) { throw new \DomainException( - 'Unrecognized queue specified: ' . $envelope->getName() + 'Unrecognized queue specified: '.$envelope->getName() ); } @@ -203,6 +200,6 @@ protected function verifyEnvelope(Envelope $envelope) if (isset($this->queues[$queue])) { return; } - throw new \DomainException('Unrecognized queue specified: ' . $queue); + throw new \DomainException('Unrecognized queue specified: '.$queue); } } diff --git a/src/QueueFactory.php b/src/QueueFactory.php index eab6be16..2d306cde 100644 --- a/src/QueueFactory.php +++ b/src/QueueFactory.php @@ -5,8 +5,6 @@ /** * Knows how to create queues and retrieve them from the used connection. * Every queue it creates is saved locally. - * - * @package Bernard */ interface QueueFactory extends \Countable { diff --git a/src/QueueFactory/InMemoryFactory.php b/src/QueueFactory/InMemoryFactory.php index 7e22ddc3..8e3bc7bd 100644 --- a/src/QueueFactory/InMemoryFactory.php +++ b/src/QueueFactory/InMemoryFactory.php @@ -6,9 +6,7 @@ /** * This is an in memory queue factory. It creates SplQueue objects for the - * queue. This also means it is not possible to introspect with Juno - * - * @package Bernard + * queue. This also means it is not possible to introspect with Juno. */ class InMemoryFactory implements \Bernard\QueueFactory { diff --git a/src/QueueFactory/PersistentFactory.php b/src/QueueFactory/PersistentFactory.php index f66b2da5..0ed4ec6a 100644 --- a/src/QueueFactory/PersistentFactory.php +++ b/src/QueueFactory/PersistentFactory.php @@ -9,8 +9,6 @@ /** * Knows how to create queues and retrieve them from the used driver. * Every queue it creates is saved locally. - * - * @package Bernard */ class PersistentFactory implements \Bernard\QueueFactory { diff --git a/src/Router.php b/src/Router.php index 814099cf..623128e1 100644 --- a/src/Router.php +++ b/src/Router.php @@ -2,9 +2,6 @@ namespace Bernard; -/** - * @package Bernard - */ interface Router { /** diff --git a/src/Router/ClassNameRouter.php b/src/Router/ClassNameRouter.php index c2480fa7..a791972f 100644 --- a/src/Router/ClassNameRouter.php +++ b/src/Router/ClassNameRouter.php @@ -5,9 +5,6 @@ use Bernard\Envelope; use Bernard\Exception\ReceiverNotFoundException; -/** - * @package Bernard - */ class ClassNameRouter extends SimpleRouter { /** diff --git a/src/Router/ContainerAwareRouter.php b/src/Router/ContainerAwareRouter.php index 71c1adba..e3e3e0a1 100644 --- a/src/Router/ContainerAwareRouter.php +++ b/src/Router/ContainerAwareRouter.php @@ -4,9 +4,6 @@ use Symfony\Component\DependencyInjection\ContainerInterface; -/** - * @package Bernard - */ class ContainerAwareRouter extends SimpleRouter { private $container; diff --git a/src/Router/LeagueContainerAwareRouter.php b/src/Router/LeagueContainerAwareRouter.php index 4774e2ba..3ebd4a50 100644 --- a/src/Router/LeagueContainerAwareRouter.php +++ b/src/Router/LeagueContainerAwareRouter.php @@ -4,9 +4,6 @@ use League\Container\ContainerInterface; -/** - * @package Bernard - */ class LeagueContainerAwareRouter extends SimpleRouter { private $container; @@ -15,7 +12,7 @@ class LeagueContainerAwareRouter extends SimpleRouter * @param ContainerInterface $container * @param array $receivers */ - public function __construct(ContainerInterface $container, array $receivers = array()) + public function __construct(ContainerInterface $container, array $receivers = []) { $this->container = $container; diff --git a/src/Router/PimpleAwareRouter.php b/src/Router/PimpleAwareRouter.php index e19dd16e..a429fe09 100644 --- a/src/Router/PimpleAwareRouter.php +++ b/src/Router/PimpleAwareRouter.php @@ -4,9 +4,6 @@ use Pimple; -/** - * @package Bernard - */ class PimpleAwareRouter extends SimpleRouter { protected $pimple; diff --git a/src/Router/SimpleRouter.php b/src/Router/SimpleRouter.php index dba86d0b..99973de4 100644 --- a/src/Router/SimpleRouter.php +++ b/src/Router/SimpleRouter.php @@ -7,8 +7,6 @@ /** * Routes a Envelope to a Receiver by using the name of the Envelope. - * - * @package Bernard */ class SimpleRouter implements \Bernard\Router { @@ -52,7 +50,7 @@ public function map(Envelope $envelope) return $receiver; } - return array($receiver, lcfirst($envelope->getName())); + return [$receiver, lcfirst($envelope->getName())]; } /** diff --git a/src/Serializer.php b/src/Serializer.php index ada8783b..fe6fc468 100644 --- a/src/Serializer.php +++ b/src/Serializer.php @@ -4,9 +4,6 @@ use Normalt\Normalizer\AggregateNormalizer; -/** - * @package Bernard - */ class Serializer { protected $aggregate; diff --git a/src/Util.php b/src/Util.php index 8594c415..698ab5a9 100644 --- a/src/Util.php +++ b/src/Util.php @@ -2,9 +2,6 @@ namespace Bernard; -/** - * @package Bernard - */ class Util { /** diff --git a/tests/Command/ConsumeCommandTest.php b/tests/Command/ConsumeCommandTest.php index 2d1037d1..fda4bb47 100644 --- a/tests/Command/ConsumeCommandTest.php +++ b/tests/Command/ConsumeCommandTest.php @@ -10,7 +10,7 @@ class ConsumeCommandTest extends \PHPUnit\Framework\TestCase { public function setUp() { - $this->queues = new InMemoryFactory; + $this->queues = new InMemoryFactory(); $this->consumer = $this->getMockBuilder('Bernard\Consumer') ->disableOriginalConstructor()->getMock(); } @@ -23,43 +23,43 @@ public function testItConsumes() $command = new ConsumeCommand($this->consumer, $this->queues); $queue = $this->queues->create('send-newsletter'); - $this->consumer->expects($this->once())->method('consume')->with($this->identicalTo($queue), $this->equalTo(array( + $this->consumer->expects($this->once())->method('consume')->with($this->identicalTo($queue), $this->equalTo([ 'max-runtime' => 100, 'max-messages' => 10, 'stop-when-empty' => true, 'stop-on-error' => false, - ))); + ])); $tester = new CommandTester($command); - $tester->execute(array( + $tester->execute([ '--max-runtime' => 100, '--max-messages' => 10, '--stop-when-empty' => true, '--stop-on-error' => false, 'queue' => 'send-newsletter', - )); + ]); } public function testItConsumesRoundRobin() { $command = new ConsumeCommand($this->consumer, $this->queues); - $args = array( + $args = [ 'max-runtime' => 100, 'max-messages' => 10, 'stop-when-empty' => true, 'stop-on-error' => false, - ); + ]; $this->consumer->expects($this->once())->method('consume')->with($this->isInstanceOf('Bernard\Queue\RoundRobinQueue'), $args); $tester = new CommandTester($command); - $tester->execute(array( + $tester->execute([ '--max-runtime' => 100, '--max-messages' => 10, '--stop-when-empty' => true, '--stop-on-error' => false, 'queue' => ['queue-1', 'queue-2'], - )); + ]); } } diff --git a/tests/Command/ProduceCommandTest.php b/tests/Command/ProduceCommandTest.php index 4f45c1c7..af08eda6 100644 --- a/tests/Command/ProduceCommandTest.php +++ b/tests/Command/ProduceCommandTest.php @@ -24,9 +24,9 @@ public function testProduceMessageWithNoArguments() $this->producer->expects($this->once())->method('produce')->with($this->equalTo($message)); $tester = new CommandTester($command); - $tester->execute(array( - 'name' => 'SendNewsletter' - )); + $tester->execute([ + 'name' => 'SendNewsletter', + ]); } /** @@ -37,23 +37,23 @@ public function testInvalidJsonThrowsException() $command = new ProduceCommand($this->producer); $tester = new CommandTester($command); - $tester->execute(array( - 'name' => 'SendNewsletter', - 'message' => '{@*^#"foo":"bar"}' - )); + $tester->execute([ + 'name' => 'SendNewsletter', + 'message' => '{@*^#"foo":"bar"}', + ]); } public function testItProducesMessageWithData() { $command = new ProduceCommand($this->producer); - $message = new PlainMessage('SendNewsletter', array('foo' => 'bar')); + $message = new PlainMessage('SendNewsletter', ['foo' => 'bar']); $this->producer->expects($this->once())->method('produce')->with($this->equalTo($message)); $tester = new CommandTester($command); - $tester->execute(array( - 'name' => 'SendNewsletter', - 'message' => '{"foo":"bar"}' - )); + $tester->execute([ + 'name' => 'SendNewsletter', + 'message' => '{"foo":"bar"}', + ]); } } diff --git a/tests/ConsumerTest.php b/tests/ConsumerTest.php index d0e06268..feba12c7 100644 --- a/tests/ConsumerTest.php +++ b/tests/ConsumerTest.php @@ -30,8 +30,8 @@ class ConsumerTest extends \PHPUnit\Framework\TestCase public function setUp() { - $this->router = new SimpleRouter; - $this->router->add('ImportUsers', new Fixtures\Service); + $this->router = new SimpleRouter(); + $this->router->add('ImportUsers', new Fixtures\Service()); $this->dispatcher = $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); $this->consumer = new Consumer($this->router, $this->dispatcher); @@ -41,7 +41,7 @@ public function testEmitsConsumeEvent() { $envelope = new Envelope(new PlainMessage('ImportUsers')); $queue = $this->getMockBuilder('Bernard\Queue\InMemoryQueue')->setMethods([ - 'dequeue' + 'dequeue', ])->setConstructorArgs(['queue'])->getMock(); $queue->expects($this->once()) @@ -110,9 +110,9 @@ public function testMaxRuntime() { $queue = new InMemoryQueue('queue'); - $this->assertFalse($this->consumer->tick($queue, array( + $this->assertFalse($this->consumer->tick($queue, [ 'max-runtime' => -1 * PHP_INT_MAX, - ))); + ])); } public function testNoEnvelopeInQueue() @@ -139,29 +139,29 @@ public function testEnvelopeIsAcknowledged() public function testMaxMessages() { - $this->router->add('ImportUsers', new Fixtures\Service); + $this->router->add('ImportUsers', new Fixtures\Service()); $queue = new InMemoryQueue('send-newsletter'); $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); - $this->assertFalse($this->consumer->tick($queue, array('max-messages' => 1))); + $this->assertFalse($this->consumer->tick($queue, ['max-messages' => 1])); $this->assertTrue($this->consumer->tick($queue)); - $this->assertTrue($this->consumer->tick($queue, array('max-messages' => 100))); + $this->assertTrue($this->consumer->tick($queue, ['max-messages' => 100])); } public function testStopAfterLastMessage() { - $this->router->add('ImportUsers', new Fixtures\Service); + $this->router->add('ImportUsers', new Fixtures\Service()); $queue = new InMemoryQueue('send-newsletter'); $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); - $this->assertTrue($this->consumer->tick($queue, array('stop-when-empty' => true))); - $this->assertTrue($this->consumer->tick($queue, array('stop-when-empty' => true))); - $this->assertFalse($this->consumer->tick($queue, array('stop-when-empty' => true))); + $this->assertTrue($this->consumer->tick($queue, ['stop-when-empty' => true])); + $this->assertTrue($this->consumer->tick($queue, ['stop-when-empty' => true])); + $this->assertFalse($this->consumer->tick($queue, ['stop-when-empty' => true])); } /** @@ -169,12 +169,12 @@ public function testStopAfterLastMessage() */ public function testStopOnError() { - $this->router->add('ImportUsers', new Fixtures\Service); + $this->router->add('ImportUsers', new Fixtures\Service()); $queue = new InMemoryQueue('send-newsletter'); $queue->enqueue(new Envelope(new PlainMessage('DifferentMessageKey'))); - $this->consumer->tick($queue, array('stop-on-error' => true)); + $this->consumer->tick($queue, ['stop-on-error' => true]); $this->assertEquals(1, $queue->count()); } @@ -202,7 +202,7 @@ public function testEnvelopeWillBeInvoked() */ public function testWillRejectDispatchOnThrowableError() { - $this->router->add('ImportReport', new Fixtures\Service); + $this->router->add('ImportReport', new Fixtures\Service()); $queue = new InMemoryQueue('send-newsletter'); $queue->enqueue(new Envelope(new PlainMessage('ImportReport'))); diff --git a/tests/Driver/Amqp/DriverTest.php b/tests/Driver/Amqp/DriverTest.php index 2416ffb2..5b68594e 100644 --- a/tests/Driver/Amqp/DriverTest.php +++ b/tests/Driver/Amqp/DriverTest.php @@ -30,21 +30,21 @@ final class DriverTest extends TestCase protected function setUp() { $this->phpAmqpChannel = $this->getMockBuilder('\PhpAmqpLib\Channel\AMQPChannel') - ->setMethods(array( + ->setMethods([ 'basic_publish', 'basic_get', 'basic_ack', 'exchange_declare', 'queue_declare', - 'queue_bind' - )) + 'queue_bind', + ]) ->disableOriginalConstructor() ->getMock(); $this->phpAmqpConnection = $this->getMockBuilder('\PhpAmqpLib\Connection\AMQPStreamConnection') - ->setMethods(array( + ->setMethods([ 'channel', - )) + ]) ->disableOriginalConstructor() ->getMock(); @@ -99,7 +99,7 @@ public function testItUsesDefaultParameters() $this->driver = new Driver( $this->phpAmqpConnection, self::EXCHANGE_NAME, - array('delivery_mode' => 2) + ['delivery_mode' => 2] ); $this->phpAmqpChannel diff --git a/tests/Driver/AppEngine/DriverTest.php b/tests/Driver/AppEngine/DriverTest.php index 3efceb0b..6918cb27 100644 --- a/tests/Driver/AppEngine/DriverTest.php +++ b/tests/Driver/AppEngine/DriverTest.php @@ -19,21 +19,21 @@ class_alias('Bernard\Tests\Fixtures\PushTask', 'google\appengine\api\taskqueue\P public function setUp() { - $this->driver = new Driver(array( + $this->driver = new Driver([ 'send-newsletter' => '/url_endpoint', - )); + ]); } public function tearDown() { - PushTask::$messages = array(); + PushTask::$messages = []; } public function testItQueuesPushTask() { $this->driver->pushMessage('send-newsletter', 'message'); - $message = new PushTask('/url_endpoint', array('message' => 'message')); + $message = new PushTask('/url_endpoint', ['message' => 'message']); $this->assertEquals($message, PushTask::$messages['send-newsletter'][0]); } @@ -42,10 +42,10 @@ public function testItUsesDefaultEndpointWhenAliasArentThere() $this->driver->pushMessage('import-users', 'message'); $this->driver->pushMessage('calculate-reports', 'message'); - $messages = array( - new PushTask('/_ah/queue/import-users', array('message' => 'message')), - new PushTask('/_ah/queue/calculate-reports', array('message' => 'message')), - ); + $messages = [ + new PushTask('/_ah/queue/import-users', ['message' => 'message']), + new PushTask('/_ah/queue/calculate-reports', ['message' => 'message']), + ]; $this->assertEquals($messages[0], PushTask::$messages['import-users'][0]); $this->assertEquals($messages[1], PushTask::$messages['calculate-reports'][0]); @@ -53,6 +53,6 @@ public function testItUsesDefaultEndpointWhenAliasArentThere() public function testListQueues() { - $this->assertEquals(array('/url_endpoint' => 'send-newsletter'), $this->driver->listQueues()); + $this->assertEquals(['/url_endpoint' => 'send-newsletter'], $this->driver->listQueues()); } } diff --git a/tests/Driver/Doctrine/AbstractDriverTest.php b/tests/Driver/Doctrine/AbstractDriverTest.php index d280be3e..52099e97 100644 --- a/tests/Driver/Doctrine/AbstractDriverTest.php +++ b/tests/Driver/Doctrine/AbstractDriverTest.php @@ -65,17 +65,17 @@ public function testCreateAndRemoveQueue() $this->driver->createQueue('send-newsletter'); $this->driver->createQueue('import-users'); - $this->assertEquals(array('import-users', 'send-newsletter'), $this->driver->listQueues()); + $this->assertEquals(['import-users', 'send-newsletter'], $this->driver->listQueues()); $this->driver->removeQueue('import-users'); - $this->assertEquals(array('send-newsletter'), $this->driver->listQueues()); + $this->assertEquals(['send-newsletter'], $this->driver->listQueues()); } public function testPushMessageLazilyCreatesQueue() { $this->driver->pushMessage('send-newsletter', 'something'); - $this->assertEquals(array('send-newsletter'), $this->driver->listQueues()); + $this->assertEquals(['send-newsletter'], $this->driver->listQueues()); } public function testRemoveQueueRemovesMessages() @@ -92,6 +92,7 @@ public function testItIsAQueue() { $messages = array_map(function ($i) { $this->driver->pushMessage('send-newsletter', $message = 'my-message-'.$i); + return $message; }, range(1, 6)); @@ -138,7 +139,7 @@ public function testListQueues() $this->driver->pushMessage('import', 'message1'); $this->driver->pushMessage('send-newsletter', 'message2'); - $this->assertEquals(array('import', 'send-newsletter'), $this->driver->listQueues()); + $this->assertEquals(['import', 'send-newsletter'], $this->driver->listQueues()); } public function testRemoveQueue() @@ -161,11 +162,11 @@ protected function setUpDatabase() { $this->connection = $this->createConnection(); - $schema = new Schema; + $schema = new Schema(); MessagesSchema::create($schema); - array_map(array($this->connection, 'executeQuery'), $schema->toSql($this->connection->getDatabasePlatform())); + array_map([$this->connection, 'executeQuery'], $schema->toSql($this->connection->getDatabasePlatform())); } /** diff --git a/tests/Driver/Doctrine/Command/BaseCommandTest.php b/tests/Driver/Doctrine/Command/BaseCommandTest.php index 0d0c312a..e768b277 100644 --- a/tests/Driver/Doctrine/Command/BaseCommandTest.php +++ b/tests/Driver/Doctrine/Command/BaseCommandTest.php @@ -25,7 +25,7 @@ public function setUp() ->method('getConnection') ->will($this->returnValue($connection)); - $this->command = $this->getMockBuilder('Bernard\\Driver\\Doctrine\\Command\\' . $this->getShortClassName()) + $this->command = $this->getMockBuilder('Bernard\\Driver\\Doctrine\\Command\\'.$this->getShortClassName()) ->setMethods(['getSynchronizer', 'getHelper']) ->setConstructorArgs([$connection]) ->getMock(); diff --git a/tests/Driver/Doctrine/ConnectionListenerTest.php b/tests/Driver/Doctrine/ConnectionListenerTest.php index fedf111a..9ceb9a7c 100644 --- a/tests/Driver/Doctrine/ConnectionListenerTest.php +++ b/tests/Driver/Doctrine/ConnectionListenerTest.php @@ -3,8 +3,6 @@ namespace Bernard\Tests\Driver\Doctrine; use Bernard\Driver\Doctrine\ConnectionListener; -use Doctrine\DBAL\Connection; -use Doctrine\DBAL\Platforms\SqlitePlatform; use Doctrine\DBAL\DBALException; class ConnectionListenerTest extends \PHPUnit\Framework\TestCase diff --git a/tests/Driver/Doctrine/MySQLDriverTest.php b/tests/Driver/Doctrine/MySQLDriverTest.php index 993ab17c..5a859833 100644 --- a/tests/Driver/Doctrine/MySQLDriverTest.php +++ b/tests/Driver/Doctrine/MySQLDriverTest.php @@ -16,23 +16,23 @@ protected function isSupported() public function testInfo() { - $params = array( - 'driver' => 'pdo_mysql', - 'host' => '127.0.0.1', - 'dbname' => 'bernard_test', - ); + $params = [ + 'driver' => 'pdo_mysql', + 'host' => '127.0.0.1', + 'dbname' => 'bernard_test', + ]; $this->assertEquals($params, $this->driver->info()); } protected function createConnection() { - return DriverManager::getConnection(array( - 'driver' => 'pdo_mysql', - 'host' => '127.0.0.1', - 'user' => 'root', - 'dbname' => 'bernard_test', + return DriverManager::getConnection([ + 'driver' => 'pdo_mysql', + 'host' => '127.0.0.1', + 'user' => 'root', + 'dbname' => 'bernard_test', 'password' => '', - )); + ]); } } diff --git a/tests/Driver/Doctrine/PostgreSQLDriverTest.php b/tests/Driver/Doctrine/PostgreSQLDriverTest.php index dbf72b08..8339dfb9 100644 --- a/tests/Driver/Doctrine/PostgreSQLDriverTest.php +++ b/tests/Driver/Doctrine/PostgreSQLDriverTest.php @@ -16,21 +16,21 @@ protected function isSupported() public function testInfo() { - $params = array( - 'driver' => 'pdo_pgsql', - 'dbname' => 'bernard_test', - ); + $params = [ + 'driver' => 'pdo_pgsql', + 'dbname' => 'bernard_test', + ]; $this->assertEquals($params, $this->driver->info()); } protected function createConnection() { - return DriverManager::getConnection(array( - 'driver' => 'pdo_pgsql', - 'user' => 'postgres', - 'dbname' => 'bernard_test', + return DriverManager::getConnection([ + 'driver' => 'pdo_pgsql', + 'user' => 'postgres', + 'dbname' => 'bernard_test', 'password' => '', - )); + ]); } } diff --git a/tests/Driver/Doctrine/SQLiteDriverTest.php b/tests/Driver/Doctrine/SQLiteDriverTest.php index b4bcf66f..13b7d9bd 100644 --- a/tests/Driver/Doctrine/SQLiteDriverTest.php +++ b/tests/Driver/Doctrine/SQLiteDriverTest.php @@ -16,19 +16,19 @@ protected function isSupported() public function testInfo() { - $params = array( - 'memory' => true, - 'driver' => 'pdo_sqlite', - ); + $params = [ + 'memory' => true, + 'driver' => 'pdo_sqlite', + ]; $this->assertEquals($params, $this->driver->info()); } protected function createConnection() { - return DriverManager::getConnection(array( - 'memory' => true, - 'driver' => 'pdo_sqlite', - )); + return DriverManager::getConnection([ + 'memory' => true, + 'driver' => 'pdo_sqlite', + ]); } } diff --git a/tests/Driver/FlatFile/DriverTest.php b/tests/Driver/FlatFile/DriverTest.php index cb447208..cc9094ed 100644 --- a/tests/Driver/FlatFile/DriverTest.php +++ b/tests/Driver/FlatFile/DriverTest.php @@ -87,7 +87,7 @@ public function testPopMessage() $this->driver->pushMessage('send-newsletter', 'job #3'); foreach (range(3, 1) as $i) { - list($message, ) = $this->driver->popMessage('send-newsletter'); + list($message) = $this->driver->popMessage('send-newsletter'); $this->assertEquals('job #'.$i, $message); } } @@ -109,7 +109,7 @@ public function testPeekQueue() { $this->driver->createQueue('send-newsletter'); - for ($i = 0; $i < 10; $i++) { + for ($i = 0; $i < 10; ++$i) { $this->driver->pushMessage('send-newsletter', 'Job #'.$i); } diff --git a/tests/Driver/InMemory/DriverTest.php b/tests/Driver/InMemory/DriverTest.php index 5c7dd15e..75349254 100644 --- a/tests/Driver/InMemory/DriverTest.php +++ b/tests/Driver/InMemory/DriverTest.php @@ -9,24 +9,24 @@ */ final class DriverTest extends \PHPUnit\Framework\TestCase { - /** - * @var Driver - */ - private $driver; + /** + * @var Driver + */ + private $driver; - protected function setUp() - { - $this->driver = new Driver(); - } + protected function setUp() + { + $this->driver = new Driver(); + } - /** - *@test - */ - function it_lists_queues() - { - $this->driver->createQueue('queue1'); - $this->driver->createQueue('queue2'); + /** + *@test + */ + public function it_lists_queues() + { + $this->driver->createQueue('queue1'); + $this->driver->createQueue('queue2'); - $this->assertEquals(['queue1', 'queue2'], $this->driver->listQueues()); - } + $this->assertEquals(['queue1', 'queue2'], $this->driver->listQueues()); + } } diff --git a/tests/Driver/Interop/DriverTest.php b/tests/Driver/Interop/DriverTest.php index 79cfed9f..f11fe460 100644 --- a/tests/Driver/Interop/DriverTest.php +++ b/tests/Driver/Interop/DriverTest.php @@ -172,7 +172,7 @@ public function testAcknowledgeMessage() $driver = new Driver($context); - $result = $driver->popMessage('theQueueName'); + $result = $driver->popMessage('theQueueName'); //guard $this->assertSame($message, $result[1]); diff --git a/tests/Driver/IronMQ/DriverTest.php b/tests/Driver/IronMQ/DriverTest.php index 73d9e8fb..fb0349db 100644 --- a/tests/Driver/IronMQ/DriverTest.php +++ b/tests/Driver/IronMQ/DriverTest.php @@ -17,7 +17,7 @@ class DriverTest extends \PHPUnit\Framework\TestCase public function setUp() { $this->ironmq = $this->getMockBuilder(IronMQ::class) - ->setMethods(array( + ->setMethods([ 'getQueue', 'getQueues', 'peekMessages', @@ -25,7 +25,7 @@ public function setUp() 'postMessage', 'getMessages', 'deleteMessage', - )) + ]) ->disableOriginalConstructor() ->getMock(); @@ -36,8 +36,8 @@ public function testItExposesInfo() { $driver = new Driver($this->ironmq, 10); - $this->assertEquals(array('prefetch' => 10), $driver->info()); - $this->assertEquals(array('prefetch' => 2), $this->driver->info()); + $this->assertEquals(['prefetch' => 10], $driver->info()); + $this->assertEquals(['prefetch' => 2], $this->driver->info()); } public function testItImplementsDriverInterface() @@ -48,7 +48,7 @@ public function testItImplementsDriverInterface() public function testItCountsNumberOfMessagesInQueue() { $this->ironmq->expects($this->at(0))->method('getQueue') - ->with($this->equalTo('send-newsletter'))->will($this->returnValue((object) array('size' => 4))); + ->with($this->equalTo('send-newsletter'))->will($this->returnValue((object) ['size' => 4])); $this->ironmq->expects($this->at(1))->method('getQueue') ->with($this->equalTo('non-existant'))->will($this->returnValue(null)); @@ -59,15 +59,15 @@ public function testItCountsNumberOfMessagesInQueue() public function testItListQueues() { - $ironmqQueues = array( - (object) array('name' => 'failed'), - (object) array('name' => 'queue1'), - ); + $ironmqQueues = [ + (object) ['name' => 'failed'], + (object) ['name' => 'queue1'], + ]; $this->ironmq->expects($this->once())->method('getQueues') ->will($this->returnValue($ironmqQueues)); - $this->assertEquals(array('failed', 'queue1'), $this->driver->listQueues()); + $this->assertEquals(['failed', 'queue1'], $this->driver->listQueues()); } public function testAcknowledgeMessage() @@ -80,17 +80,17 @@ public function testAcknowledgeMessage() public function testItPeeksInAQueue() { - $ironmqMessages = array( - (object) array('body' => 'message1'), - ); + $ironmqMessages = [ + (object) ['body' => 'message1'], + ]; $this->ironmq->expects($this->at(0))->method('peekMessages') ->with($this->equalTo('my-queue'), $this->equalTo(10))->will($this->returnValue($ironmqMessages)); $this->ironmq->expects($this->at(1))->method('peekMessages') ->with($this->equalTo('my-queue2'), $this->equalTo(20))->will($this->returnValue(null)); - $this->assertEquals(array('message1'), $this->driver->peekQueue('my-queue', 10, 10)); - $this->assertEquals(array(), $this->driver->peekQueue('my-queue2')); + $this->assertEquals(['message1'], $this->driver->peekQueue('my-queue', 10, 10)); + $this->assertEquals([], $this->driver->peekQueue('my-queue2')); } public function testItRemovesAQueue() @@ -115,17 +115,17 @@ public function testItPushesMessages() public function testItPrefetchesMessages() { - $ironmqMessages = array( - (object) array('body' => 'message1', 'id' => 1), - (object) array('body' => 'message2', 'id' => 2), - ); + $ironmqMessages = [ + (object) ['body' => 'message1', 'id' => 1], + (object) ['body' => 'message2', 'id' => 2], + ]; $this->ironmq->expects($this->once())->method('getMessages') ->with($this->equalTo('send-newsletter'), $this->equalTo(2)) ->will($this->returnValue($ironmqMessages)); - $this->assertEquals(array('message1', 1), $this->driver->popMessage('send-newsletter')); - $this->assertEquals(array('message2', 2), $this->driver->popMessage('send-newsletter')); + $this->assertEquals(['message1', 1], $this->driver->popMessage('send-newsletter')); + $this->assertEquals(['message2', 2], $this->driver->popMessage('send-newsletter')); } public function testItPopMessages() @@ -134,24 +134,24 @@ public function testItPopMessages() ->expects($this->at(0)) ->method('getMessages') ->with($this->equalTo('my-queue1'), $this->equalTo(2), $this->equalTo(60)) - ->will($this->returnValue(array( - (object) array('body' => 'message1', 'id' => 1), - ))); + ->will($this->returnValue([ + (object) ['body' => 'message1', 'id' => 1], + ])); $this->ironmq ->expects($this->at(1)) ->method('getMessages') ->with($this->equalTo('my-queue2'), $this->equalTo(2), $this->equalTo(60)) - ->will($this->returnValue(array( - (object) array('body' => 'message2', 'id' => 2), - ))); + ->will($this->returnValue([ + (object) ['body' => 'message2', 'id' => 2], + ])); $this->ironmq ->expects($this->at(1)) ->method('getMessages') ->with($this->equalTo('my-queue2'), $this->equalTo(2), $this->equalTo(60)) ->will($this->returnValue(null)); - $this->assertEquals(array('message1', 1), $this->driver->popMessage('my-queue1')); - $this->assertEquals(array('message2', 2), $this->driver->popMessage('my-queue2')); - $this->assertEquals(array(null, null), $this->driver->popMessage('my-queue2', 0.01)); + $this->assertEquals(['message1', 1], $this->driver->popMessage('my-queue1')); + $this->assertEquals(['message2', 2], $this->driver->popMessage('my-queue2')); + $this->assertEquals([null, null], $this->driver->popMessage('my-queue2', 0.01)); } } diff --git a/tests/Driver/MongoDB/DriverFunctionalTest.php b/tests/Driver/MongoDB/DriverFunctionalTest.php index 593b7483..2eaaea27 100644 --- a/tests/Driver/MongoDB/DriverFunctionalTest.php +++ b/tests/Driver/MongoDB/DriverFunctionalTest.php @@ -8,7 +8,7 @@ use MongoConnectionException; /** - * @coversDefaultClass Bernard\Driver\MongoDB\Driver + * @coversDefaultClass \Bernard\Driver\MongoDB\Driver * @group functional */ class DriverFunctionalTest extends \PHPUnit\Framework\TestCase @@ -28,7 +28,7 @@ class DriverFunctionalTest extends \PHPUnit\Framework\TestCase public function setUp() { - if ( ! class_exists('MongoClient')) { + if (!class_exists('MongoClient')) { $this->markTestSkipped('MongoDB extension is not available.'); } @@ -45,7 +45,7 @@ public function setUp() public function tearDown() { - if ( ! $this->messages instanceof MongoCollection) { + if (!$this->messages instanceof MongoCollection) { return; } @@ -98,11 +98,11 @@ public function testPeekQueue() $this->driver->pushMessage('foo', 'message1'); $this->driver->pushMessage('foo', 'message2'); - $this->assertSame(array('message1', 'message2'), $this->driver->peekQueue('foo')); - $this->assertSame(array('message2'), $this->driver->peekQueue('foo', 1)); - $this->assertSame(array(), $this->driver->peekQueue('foo', 2)); - $this->assertSame(array('message1'), $this->driver->peekQueue('foo', 0, 1)); - $this->assertSame(array('message2'), $this->driver->peekQueue('foo', 1, 1)); + $this->assertSame(['message1', 'message2'], $this->driver->peekQueue('foo')); + $this->assertSame(['message2'], $this->driver->peekQueue('foo', 1)); + $this->assertSame([], $this->driver->peekQueue('foo', 2)); + $this->assertSame(['message1'], $this->driver->peekQueue('foo', 0, 1)); + $this->assertSame(['message2'], $this->driver->peekQueue('foo', 1, 1)); } /** @@ -145,15 +145,15 @@ public function testCreateQueueWithDuplicateNameIsNoop() $this->driver->createQueue('foo'); $this->driver->createQueue('foo'); - $this->assertSame(array('foo'), $this->driver->listQueues()); + $this->assertSame(['foo'], $this->driver->listQueues()); } public function testInfo() { - $info = array( - 'messages' => self::DATABASE . '.' . self::MESSAGES, - 'queues' => self::DATABASE . '.' . self::QUEUES, - ); + $info = [ + 'messages' => self::DATABASE.'.'.self::MESSAGES, + 'queues' => self::DATABASE.'.'.self::QUEUES, + ]; $this->assertSame($info, $this->driver->info()); } diff --git a/tests/Driver/MongoDB/DriverTest.php b/tests/Driver/MongoDB/DriverTest.php index 14d3a0e8..1db4287d 100644 --- a/tests/Driver/MongoDB/DriverTest.php +++ b/tests/Driver/MongoDB/DriverTest.php @@ -20,7 +20,7 @@ class DriverTest extends \PHPUnit\Framework\TestCase public function setUp() { - if ( ! class_exists('MongoCollection')) { + if (!class_exists('MongoCollection')) { $this->markTestSkipped('MongoDB extension is not available.'); } @@ -34,16 +34,16 @@ public function testListQueues() $this->queues->expects($this->once()) ->method('distinct') ->with('_id') - ->will($this->returnValue(array('foo', 'bar'))); + ->will($this->returnValue(['foo', 'bar'])); - $this->assertSame(array('foo', 'bar'), $this->driver->listQueues()); + $this->assertSame(['foo', 'bar'], $this->driver->listQueues()); } public function testCreateQueue() { $this->queues->expects($this->once()) ->method('update') - ->with(array('_id' => 'foo'), array('_id' => 'foo'), array('upsert' => true)); + ->with(['_id' => 'foo'], ['_id' => 'foo'], ['upsert' => true]); $this->driver->createQueue('foo'); } @@ -52,7 +52,7 @@ public function testCountMessages() { $this->messages->expects($this->once()) ->method('count') - ->with(array('queue' => 'foo', 'visible' => true)) + ->with(['queue' => 'foo', 'visible' => true]) ->will($this->returnValue(2)); $this->assertSame(2, $this->driver->countMessages('foo')); @@ -62,7 +62,7 @@ public function testPushMessage() { $this->messages->expects($this->once()) ->method('insert') - ->with($this->callback(function($data) { + ->with($this->callback(function ($data) { return $data['queue'] === 'foo' && $data['message'] === 'message1' && $data['sentAt'] instanceof MongoDate && @@ -77,12 +77,12 @@ public function testPopMessageWithFoundMessage() $this->messages->expects($this->atLeastOnce()) ->method('findAndModify') ->with( - array('queue' => 'foo', 'visible' => true), - array('$set' => array('visible' => false)), - array('message' => 1), - array('sort' => array('sentAt' => 1)) + ['queue' => 'foo', 'visible' => true], + ['$set' => ['visible' => false]], + ['message' => 1], + ['sort' => ['sentAt' => 1]] ) - ->will($this->returnValue(array('message' => 'message1', '_id' => '000000000000000000000000'))); + ->will($this->returnValue(['message' => 'message1', '_id' => '000000000000000000000000'])); list($message, $receipt) = $this->driver->popMessage('foo'); $this->assertSame('message1', $message); @@ -97,10 +97,10 @@ public function testPopMessageWithMissingMessage() $this->messages->expects($this->atLeastOnce()) ->method('findAndModify') ->with( - array('queue' => 'foo', 'visible' => true), - array('$set' => array('visible' => false)), - array('message' => 1), - array('sort' => array('sentAt' => 1)) + ['queue' => 'foo', 'visible' => true], + ['$set' => ['visible' => false]], + ['message' => 1], + ['sort' => ['sentAt' => 1]] ) ->will($this->returnValue(false)); @@ -113,7 +113,7 @@ public function testAcknowledgeMessage() { $this->messages->expects($this->once()) ->method('remove') - ->with($this->callback(function($query) { + ->with($this->callback(function ($query) { return $query['_id'] instanceof MongoId && (string) $query['_id'] === '000000000000000000000000' && $query['queue'] === 'foo'; @@ -130,12 +130,12 @@ public function testPeekQueue() $this->messages->expects($this->once()) ->method('find') - ->with(array('queue' => 'foo', 'visible' => true), array('_id' => 0, 'message' => 1)) + ->with(['queue' => 'foo', 'visible' => true], ['_id' => 0, 'message' => 1]) ->will($this->returnValue($cursor)); $cursor->expects($this->at(0)) ->method('sort') - ->with(array('sentAt' => 1)) + ->with(['sentAt' => 1]) ->will($this->returnValue($cursor)); $cursor->expects($this->at(1)) @@ -148,23 +148,23 @@ public function testPeekQueue() $cursor->expects($this->at(2)) ->method('skip') ->with(0) - ->will($this->returnValue(new ArrayIterator(array( - array('message' => 'message1'), - array('message' => 'message2'), - )))); + ->will($this->returnValue(new ArrayIterator([ + ['message' => 'message1'], + ['message' => 'message2'], + ]))); - $this->assertSame(array('message1', 'message2'), $this->driver->peekQueue('foo')); + $this->assertSame(['message1', 'message2'], $this->driver->peekQueue('foo')); } public function testRemoveQueue() { $this->queues->expects($this->once()) ->method('remove') - ->with(array('_id' => 'foo')); + ->with(['_id' => 'foo']); $this->messages->expects($this->once()) ->method('remove') - ->with(array('queue' => 'foo')); + ->with(['queue' => 'foo']); $this->driver->removeQueue('foo'); } @@ -179,10 +179,10 @@ public function testInfo() ->method('__toString') ->will($this->returnValue('db.messages')); - $info = array( + $info = [ 'messages' => 'db.messages', 'queues' => 'db.queues', - ); + ]; $this->assertSame($info, $this->driver->info()); } diff --git a/tests/Driver/Pheanstalk/DriverTest.php b/tests/Driver/Pheanstalk/DriverTest.php index de330620..67004322 100644 --- a/tests/Driver/Pheanstalk/DriverTest.php +++ b/tests/Driver/Pheanstalk/DriverTest.php @@ -17,14 +17,14 @@ class DriverTest extends \PHPUnit\Framework\TestCase public function setUp() { $this->pheanstalk = $this->getMockBuilder(Pheanstalk::class) - ->setMethods(array( + ->setMethods([ 'listTubes', 'statsTube', 'putInTube', 'reserveFromTube', 'delete', 'stats', - )) + ]) ->disableOriginalConstructor() ->getMock(); @@ -35,12 +35,12 @@ public function testItExposesInfo() { $driver = new Driver($this->pheanstalk); - $info = new \ArrayObject(array('info' => true)); + $info = new \ArrayObject(['info' => true]); $this->pheanstalk->expects($this->once())->method('stats') ->will($this->returnValue($info)); - $this->assertEquals(array('info' => true), $driver->info()); + $this->assertEquals(['info' => true], $driver->info()); } public function testItImplementsDriverInterface() @@ -51,17 +51,17 @@ public function testItImplementsDriverInterface() public function testItCountsNumberOfMessagesInQueue() { $this->pheanstalk->expects($this->once())->method('statsTube') - ->with($this->equalTo('send-newsletter'))->will($this->returnValue(array('current-jobs-ready' => 4))); + ->with($this->equalTo('send-newsletter'))->will($this->returnValue(['current-jobs-ready' => 4])); $this->assertEquals(4, $this->driver->countMessages('send-newsletter')); } public function testItListQueues() { - $queues = array( + $queues = [ 'failed', 'queue1', - ); + ]; $this->pheanstalk->expects($this->once())->method('listTubes') ->will($this->returnValue($queues)); @@ -79,7 +79,7 @@ public function testAcknowledgeMessage() public function testItPeeksInAQueue() { - $this->assertEquals(array(), $this->driver->peekQueue('my-queue2')); + $this->assertEquals([], $this->driver->peekQueue('my-queue2')); } public function testItPushesMessages() @@ -110,8 +110,8 @@ public function testItPopMessages() ->with($this->equalTo('my-queue2'), $this->equalTo(5)) ->will($this->returnValue(null)); - $this->assertEquals(array('message1', $job1), $this->driver->popMessage('my-queue1')); - $this->assertEquals(array('message2', $job2), $this->driver->popMessage('my-queue2')); - $this->assertEquals(array(null, null), $this->driver->popMessage('my-queue2')); + $this->assertEquals(['message1', $job1], $this->driver->popMessage('my-queue1')); + $this->assertEquals(['message2', $job2], $this->driver->popMessage('my-queue2')); + $this->assertEquals([null, null], $this->driver->popMessage('my-queue2')); } } diff --git a/tests/Driver/PhpRedis/DriverTest.php b/tests/Driver/PhpRedis/DriverTest.php index 28659095..6d69dacf 100644 --- a/tests/Driver/PhpRedis/DriverTest.php +++ b/tests/Driver/PhpRedis/DriverTest.php @@ -12,7 +12,7 @@ public function setUp() $this->markTestSkipped('"redis" extension is not loaded.'); } - $this->redis = $this->getMockBuilder('Redis')->setMethods(array( + $this->redis = $this->getMockBuilder('Redis')->setMethods([ 'lLen', 'sMembers', 'lRange', @@ -23,7 +23,7 @@ public function setUp() 'sContains', 'rPush', 'sRem', - ))->getMock(); + ])->getMock(); $this->connection = new Driver($this->redis); } @@ -44,24 +44,23 @@ public function testItCountsNumberOfMessagesInQueue() public function testItGetsAllKeys() { $this->redis->expects($this->once())->method('sMembers')->with($this->equalTo('queues')) - ->will($this->returnValue(array('failed', 'queue1'))); + ->will($this->returnValue(['failed', 'queue1'])); - $this->assertEquals(array('failed', 'queue1'), $this->connection->listQueues()); + $this->assertEquals(['failed', 'queue1'], $this->connection->listQueues()); } public function testItPeeksInAQueue() { $this->redis->expects($this->at(0))->method('lRange') ->with($this->equalTo('queue:my-queue'), $this->equalTo(10), $this->equalTo(19)) - ->will($this->returnValue(array('message1'))); + ->will($this->returnValue(['message1'])); $this->redis->expects($this->at(1))->method('lRange') ->with($this->equalTo('queue:send-newsletter'), $this->equalTo(0), $this->equalTo(19)) - ->will($this->returnValue(array('message2'))); - - $this->assertEquals(array('message1'), $this->connection->peekQueue('my-queue', 10, 10)); - $this->assertEquals(array('message2'), $this->connection->peekQueue('send-newsletter')); + ->will($this->returnValue(['message2'])); + $this->assertEquals(['message1'], $this->connection->peekQueue('my-queue', 10, 10)); + $this->assertEquals(['message2'], $this->connection->peekQueue('send-newsletter')); } public function testItRemovesAQueue() @@ -88,13 +87,13 @@ public function testItPushesMessages() public function testItPopMessages() { - $this->redis->expects($this->at(0))->method('blPop')->with($this->equalTo(array('queue:send-newsletter'))) - ->will($this->returnValue(array('my-queue', 'message1'))); + $this->redis->expects($this->at(0))->method('blPop')->with($this->equalTo(['queue:send-newsletter'])) + ->will($this->returnValue(['my-queue', 'message1'])); - $this->redis->expects($this->at(1))->method('blPop')->with($this->equalTo(array('queue:ask-forgiveness')), $this->equalTo(30)) - ->will($this->returnValue(array('my-queue2', 'message2'))); + $this->redis->expects($this->at(1))->method('blPop')->with($this->equalTo(['queue:ask-forgiveness']), $this->equalTo(30)) + ->will($this->returnValue(['my-queue2', 'message2'])); - $this->assertEquals(array('message1', null), $this->connection->popMessage('send-newsletter')); - $this->assertEquals(array('message2', null), $this->connection->popMessage('ask-forgiveness', 30)); + $this->assertEquals(['message1', null], $this->connection->popMessage('send-newsletter')); + $this->assertEquals(['message2', null], $this->connection->popMessage('ask-forgiveness', 30)); } } diff --git a/tests/Driver/Predis/DriverTest.php b/tests/Driver/Predis/DriverTest.php index 523b0201..9744049e 100644 --- a/tests/Driver/Predis/DriverTest.php +++ b/tests/Driver/Predis/DriverTest.php @@ -11,7 +11,7 @@ public function setUp() { // Because predis uses __call all methods that needs mocking must be // explicitly defined. - $this->redis = $this->getMockBuilder(Client::class)->setMethods(array( + $this->redis = $this->getMockBuilder(Client::class)->setMethods([ 'lLen', 'sMembers', 'lRange', @@ -22,7 +22,7 @@ public function setUp() 'sContains', 'rPush', 'sRem', - ))->getMock(); + ])->getMock(); $this->connection = new Driver($this->redis); } @@ -30,12 +30,12 @@ public function setUp() public function testItPopMessages() { $this->redis->expects($this->at(0))->method('blPop')->with($this->equalTo('queue:send-newsletter')) - ->will($this->returnValue(array('my-queue', 'message1'))); + ->will($this->returnValue(['my-queue', 'message1'])); $this->redis->expects($this->at(1))->method('blPop')->with($this->equalTo('queue:ask-forgiveness'), $this->equalTo(30)) - ->will($this->returnValue(array('my-queue2', 'message2'))); + ->will($this->returnValue(['my-queue2', 'message2'])); - $this->assertEquals(array('message1', null), $this->connection->popMessage('send-newsletter')); - $this->assertEquals(array('message2', null), $this->connection->popMessage('ask-forgiveness', 30)); + $this->assertEquals(['message1', null], $this->connection->popMessage('send-newsletter')); + $this->assertEquals(['message2', null], $this->connection->popMessage('ask-forgiveness', 30)); } } diff --git a/tests/Driver/PrefetchMessageCacheTest.php b/tests/Driver/PrefetchMessageCacheTest.php index eb329ad0..f968c4b8 100644 --- a/tests/Driver/PrefetchMessageCacheTest.php +++ b/tests/Driver/PrefetchMessageCacheTest.php @@ -8,10 +8,10 @@ class PrefetchMessageCacheTest extends \PHPUnit\Framework\TestCase { public function testPushesAndPop() { - $cache = new PrefetchMessageCache; - $cache->push('my-queue', array('message1', 'r0')); + $cache = new PrefetchMessageCache(); + $cache->push('my-queue', ['message1', 'r0']); - $this->assertEquals(array('message1', 'r0'), $cache->pop('my-queue')); + $this->assertEquals(['message1', 'r0'], $cache->pop('my-queue')); $this->assertInternalType('null', $cache->pop('my-queue')); } } diff --git a/tests/Driver/Sqs/DriverTest.php b/tests/Driver/Sqs/DriverTest.php index 0b68feba..86eee016 100644 --- a/tests/Driver/Sqs/DriverTest.php +++ b/tests/Driver/Sqs/DriverTest.php @@ -10,8 +10,8 @@ class DriverTest extends \PHPUnit\Framework\TestCase { - const DUMMY_QUEUE_NAME = 'my-queue'; - const DUMMY_FIFO_QUEUE_NAME = 'my-queue.fifo'; + const DUMMY_QUEUE_NAME = 'my-queue'; + const DUMMY_FIFO_QUEUE_NAME = 'my-queue.fifo'; const DUMMY_QUEUE_URL_PREFIX = 'https://sqs.eu-west-1.amazonaws.com/123123'; /** @var \PHPUnit_Framework_MockObject_MockObject */ @@ -24,7 +24,7 @@ public function setUp() { $this->sqs = $this->getMockBuilder(SqsClient::class) ->disableOriginalConstructor() - ->setMethods(array( + ->setMethods([ 'createQueue', 'deleteQueue', 'getQueueUrl', @@ -33,7 +33,7 @@ public function setUp() 'sendMessage', 'receiveMessage', 'deleteMessage', - )) + ]) ->getMock(); $this->driver = new Driver($this->sqs, ['send-newsletter' => 'url']); @@ -79,7 +79,7 @@ public function testItCreatesFifoQueue() 'QueueName' => self::DUMMY_FIFO_QUEUE_NAME, 'Attributes' => [ 'FifoQueue' => 'true', - ] + ], ])) ->will($this->returnValue( $this->wrapResult([ @@ -99,7 +99,7 @@ public function testItDeletesQueue() $this->sqs ->expects($this->once()) ->method('deleteQueue') - ->with($this->equalTo(['QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX. '/'. self::DUMMY_QUEUE_NAME])); + ->with($this->equalTo(['QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/'.self::DUMMY_QUEUE_NAME])); $this->driver->removeQueue(self::DUMMY_QUEUE_NAME); } @@ -111,8 +111,8 @@ public function testItCountsNumberOfMessagesInQueue() ->expects($this->once()) ->method('getQueueAttributes') ->with($this->equalTo([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX. '/'. self::DUMMY_QUEUE_NAME, - 'AttributeNames' => array('ApproximateNumberOfMessages'), + 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/'.self::DUMMY_QUEUE_NAME, + 'AttributeNames' => ['ApproximateNumberOfMessages'], ])) ->will($this->returnValue( $this->wrapResult([ @@ -135,7 +135,7 @@ public function testUnresolveableQueueNameThrowsException() public function testItGetsAllQueues() { $driver = new Driver($this->sqs, [ - 'import-users' => 'alreadyknowurl/import_users_prod' + 'import-users' => 'alreadyknowurl/import_users_prod', ]); $this->sqs @@ -146,21 +146,21 @@ public function testItGetsAllQueues() 'https://sqs.eu-west-1.amazonaws.com/123123/failed', 'https://sqs.eu-west-1.amazonaws.com/123123/queue1', 'alreadyknowurl/import_users_prod', - ] + ], ]))); - $queues = array('import-users', 'failed', 'queue1'); + $queues = ['import-users', 'failed', 'queue1']; $this->assertEquals($queues, $driver->listQueues()); } public function testItPrefetchesMessages() { - $query = array( - 'QueueUrl' => 'url', + $query = [ + 'QueueUrl' => 'url', 'MaxNumberOfMessages' => 2, - 'WaitTimeSeconds' => 5, - ); + 'WaitTimeSeconds' => 5, + ]; $sqsMessages = $this->wrapResult([ 'Messages' => [ @@ -185,8 +185,8 @@ public function testItPushesMessages() ->expects($this->once()) ->method('sendMessage') ->with($this->equalTo([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX. '/'. self::DUMMY_QUEUE_NAME, - 'MessageBody' => $message + 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/'.self::DUMMY_QUEUE_NAME, + 'MessageBody' => $message, ])); $this->driver->pushMessage(self::DUMMY_QUEUE_NAME, $message); } @@ -200,11 +200,10 @@ public function testItPushesMessagesToFifoQueue() ->expects($this->once()) ->method('sendMessage') ->with($this->equalTo([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX. '/'. self::DUMMY_FIFO_QUEUE_NAME, + 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/'.self::DUMMY_FIFO_QUEUE_NAME, 'MessageBody' => $message, - 'MessageGroupId' => \Bernard\Driver\Sqs\Driver::class . '::pushMessage', + 'MessageGroupId' => \Bernard\Driver\Sqs\Driver::class.'::pushMessage', 'MessageDeduplicationId' => md5($message), - ])); $this->driver->pushMessage(self::DUMMY_FIFO_QUEUE_NAME, $message); } @@ -215,42 +214,42 @@ public function testItPopMessages() ->expects($this->at(0)) ->method('getQueueUrl') ->with($this->equalTo([ - 'QueueName' => self::DUMMY_QUEUE_NAME. '0', + 'QueueName' => self::DUMMY_QUEUE_NAME.'0', ])) ->will($this->returnValue($this->wrapResult([ 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX - . '/'. self::DUMMY_QUEUE_NAME. '0', + .'/'.self::DUMMY_QUEUE_NAME.'0', ]))); $this->sqs ->expects($this->at(1)) ->method('receiveMessage') ->with($this->equalTo([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX. '/'. self::DUMMY_QUEUE_NAME. '0', + 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/'.self::DUMMY_QUEUE_NAME.'0', 'MaxNumberOfMessages' => 2, - 'WaitTimeSeconds' => 5, + 'WaitTimeSeconds' => 5, ])) ->will($this->returnValue($this->wrapResult([ 'Messages' => [ - ['Body' => 'message0', 'ReceiptHandle' => 'r0'] - ] + ['Body' => 'message0', 'ReceiptHandle' => 'r0'], + ], ]))); $this->sqs ->expects($this->at(2)) ->method('getQueueUrl') ->with($this->equalTo([ - 'QueueName' => self::DUMMY_QUEUE_NAME. '1' + 'QueueName' => self::DUMMY_QUEUE_NAME.'1', ])) ->will($this->returnValue($this->wrapResult([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX . '/my-queue1', + 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/my-queue1', ]))); $this->sqs ->expects($this->at(3)) ->method('receiveMessage') ->with($this->equalTo([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX. '/my-queue1', + 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/my-queue1', 'MaxNumberOfMessages' => 2, - 'WaitTimeSeconds' => 30, + 'WaitTimeSeconds' => 30, ])) ->will($this->returnValue($this->wrapResult([ 'Messages' => [ @@ -282,7 +281,7 @@ private function assertSqsQueueUrl() ->with($this->equalTo(['QueueName' => self::DUMMY_QUEUE_NAME])) ->will($this->returnValue($this->wrapResult([ 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX - . '/'. self::DUMMY_QUEUE_NAME, + .'/'.self::DUMMY_QUEUE_NAME, ]))); } @@ -294,7 +293,7 @@ private function assertSqsFifoQueueUrl() ->with($this->equalTo(['QueueName' => self::DUMMY_FIFO_QUEUE_NAME])) ->will($this->returnValue($this->wrapResult([ 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX - . '/'. self::DUMMY_FIFO_QUEUE_NAME, + .'/'.self::DUMMY_FIFO_QUEUE_NAME, ]))); } diff --git a/tests/EventListener/ErrorLogSubscriberTest.php b/tests/EventListener/ErrorLogSubscriberTest.php index 2c9a7df4..8b6b2eab 100644 --- a/tests/EventListener/ErrorLogSubscriberTest.php +++ b/tests/EventListener/ErrorLogSubscriberTest.php @@ -48,7 +48,6 @@ public function testGetSubscribedEvents() public function testOnRejectException() { - $this->envelope->expects($this->once()) ->method('getName') ->willReturn('foo'); @@ -81,7 +80,7 @@ public function testOnRejectObject() $this->envelope->expects($this->once()) ->method('getName') ->willReturn('foo'); - $error = new \stdClass; + $error = new \stdClass(); $event = new RejectEnvelopeEvent($this->envelope, $this->queue, $error); $expected = ' [bernard] caught unknown error type stdClass while processing foo.'; $this->subscriber->onReject($event); diff --git a/tests/EventListener/FailureSubscriberTest.php b/tests/EventListener/FailureSubscriberTest.php index b69a2814..627467b0 100644 --- a/tests/EventListener/FailureSubscriberTest.php +++ b/tests/EventListener/FailureSubscriberTest.php @@ -27,7 +27,6 @@ public function testAcknowledgeMessageAndEnqueue() ->method('produce') ->with($message, 'failures'); - $this->subscriber->onReject(new RejectEnvelopeEvent($envelope, new InMemoryQueue('foo'), new \Exception)); - + $this->subscriber->onReject(new RejectEnvelopeEvent($envelope, new InMemoryQueue('foo'), new \Exception())); } } diff --git a/tests/Exception/ExceptionTest.php b/tests/Exception/ExceptionTest.php index 3b136ae0..255c2e9a 100644 --- a/tests/Exception/ExceptionTest.php +++ b/tests/Exception/ExceptionTest.php @@ -10,14 +10,15 @@ class ExceptionTest extends \PHPUnit\Framework\TestCase public function testThrowException($exception, $base) { try { - throw new $exception; + throw new $exception(); } catch (\Exception $e) { $this->assertInstanceOf('\Bernard\Exception\Exception', $e); $this->assertInstanceOf($exception, $e); $this->assertInstanceOf($base, $e); + return; } - $this->fail("Exception not caught"); + $this->fail('Exception not caught'); } public function exceptionProvider() diff --git a/tests/Fixtures/PushTask.php b/tests/Fixtures/PushTask.php index 877878e4..f9dc8a05 100644 --- a/tests/Fixtures/PushTask.php +++ b/tests/Fixtures/PushTask.php @@ -8,13 +8,13 @@ */ class PushTask { - public static $messages = array(); + public static $messages = []; protected $url_path; protected $query_data; protected $options; - public function __construct($url_path, array $query_data = array(), array $options = array()) + public function __construct($url_path, array $query_data = [], array $options = []) { $this->url_path = $url_path; $this->query_data = $query_data; diff --git a/tests/Fixtures/SendNewsletterMessage.php b/tests/Fixtures/SendNewsletterMessage.php index 179f2483..25c9765c 100644 --- a/tests/Fixtures/SendNewsletterMessage.php +++ b/tests/Fixtures/SendNewsletterMessage.php @@ -20,12 +20,12 @@ class SendNewsletterMessage extends AbstractMessage implements NormalizableInter */ public $newsletterId = 10; - public function normalize(NormalizerInterface $normalizer, $format = null, array $context = array()) + public function normalize(NormalizerInterface $normalizer, $format = null, array $context = []) { return get_object_vars($this); } - public function denormalize(DenormalizerInterface $denormalizer, $data, $format = null, array $context = array()) + public function denormalize(DenormalizerInterface $denormalizer, $data, $format = null, array $context = []) { $this->newsletterId = $data['newsletterId']; } diff --git a/tests/Fixtures/Service.php b/tests/Fixtures/Service.php index 4a5c994d..b259c23d 100644 --- a/tests/Fixtures/Service.php +++ b/tests/Fixtures/Service.php @@ -18,7 +18,7 @@ public function importUsers() public function createFile() { - touch(__DIR__ . '/create_file.test'); + touch(__DIR__.'/create_file.test'); } public function importReport(Report $report) diff --git a/tests/Message/AbstractMessageTest.php b/tests/Message/AbstractMessageTest.php index 164366e7..a2dd17fe 100644 --- a/tests/Message/AbstractMessageTest.php +++ b/tests/Message/AbstractMessageTest.php @@ -8,13 +8,13 @@ class AbstractMessageTest extends \PHPUnit\Framework\TestCase { public function testImplementsMessage() { - $this->assertInstanceOf('Bernard\Message', new Fixtures\SendNewsletterMessage); - $this->assertInstanceOf('Bernard\Message\AbstractMessage', new Fixtures\SendNewsletterMessage); + $this->assertInstanceOf('Bernard\Message', new Fixtures\SendNewsletterMessage()); + $this->assertInstanceOf('Bernard\Message\AbstractMessage', new Fixtures\SendNewsletterMessage()); } public function testItUsesClassNameAsNameAndQueueNameNormalized() { - $message = new Fixtures\SendNewsletterMessage(); + $message = new Fixtures\SendNewsletterMessage(); $this->assertEquals('SendNewsletter', $message->getName()); $this->assertEquals('send-newsletter', $message->getQueue()); } diff --git a/tests/Message/PlainMessageTest.php b/tests/Message/PlainMessageTest.php index 3f462bc2..71151588 100644 --- a/tests/Message/PlainMessageTest.php +++ b/tests/Message/PlainMessageTest.php @@ -15,19 +15,18 @@ public function testItHaveAName() public function testItHasArguments() { - $message = $this->createMessage('SendNewsletter', array( + $message = $this->createMessage('SendNewsletter', [ 'key1' => 1, - 'key2' => array(1,2,3,4), + 'key2' => [1, 2, 3, 4], 'key3' => null, - )); + ]); $this->assertTrue(isset($message['key1'])); $this->assertTrue(isset($message['key1'])); $this->assertEquals(1, $message['key1']); - $this->assertEquals(array(1,2,3,4), $message['key2']); + $this->assertEquals([1, 2, 3, 4], $message['key2']); $this->assertInternalType('null', $message['key3']); - } public function testItImplementsArrayAccess() diff --git a/tests/ProducerTest.php b/tests/ProducerTest.php index 157bc29b..5969c930 100644 --- a/tests/ProducerTest.php +++ b/tests/ProducerTest.php @@ -11,17 +11,17 @@ class ProducerTest extends \PHPUnit\Framework\TestCase { public function setUp() { - $this->queues = new InMemoryFactory; - $this->dispatcher = new EventDispatcher; + $this->queues = new InMemoryFactory(); + $this->dispatcher = new EventDispatcher(); $this->producer = new Producer($this->queues, $this->dispatcher); } public function testDispatchesEvent() { - $args = array(); + $args = []; $this->dispatcher->addListener('bernard.produce', function ($event) use (&$args) { - $args = array('envelope' => $event->getEnvelope(), 'queue' => $event->getQueue()); + $args = ['envelope' => $event->getEnvelope(), 'queue' => $event->getQueue()]; }); $message = new PlainMessage('Message'); diff --git a/tests/Queue/AbstractQueueTest.php b/tests/Queue/AbstractQueueTest.php index b9f0afaa..1424c189 100644 --- a/tests/Queue/AbstractQueueTest.php +++ b/tests/Queue/AbstractQueueTest.php @@ -11,12 +11,12 @@ abstract class AbstractQueueTest extends \PHPUnit\Framework\TestCase * @expectedException \Bernard\Exception\InvalidOperationexception * @expectedExceptionMessage Queue "send-newsletter" is closed. */ - public function testNotAllowedWhenClosed($method, array $arguments = array()) + public function testNotAllowedWhenClosed($method, array $arguments = []) { $queue = $this->createQueue('send-newsletter'); $queue->close(); - call_user_func_array(array($queue, $method), $arguments); + call_user_func_array([$queue, $method], $arguments); } public function testNameAsToString() @@ -29,17 +29,17 @@ public function testNameAsToString() public function dataClosedMethods() { - return array( - array('peek', array(0, 10)), - array('count'), - array('dequeue'), - array('enqueue', array( - new Envelope($this->createMock('Bernard\Message')) - )), - array('acknowledge', array( - new Envelope($this->createMock('Bernard\Message')) - )), - ); + return [ + ['peek', [0, 10]], + ['count'], + ['dequeue'], + ['enqueue', [ + new Envelope($this->createMock('Bernard\Message')), + ]], + ['acknowledge', [ + new Envelope($this->createMock('Bernard\Message')), + ]], + ]; } abstract protected function createQueue($name); diff --git a/tests/Queue/InMemoryQueueTest.php b/tests/Queue/InMemoryQueueTest.php index fe8eda59..04c4bcc8 100644 --- a/tests/Queue/InMemoryQueueTest.php +++ b/tests/Queue/InMemoryQueueTest.php @@ -24,18 +24,18 @@ public function testPeek() { $queue = new InMemoryQueue('send-newsletter'); - $this->assertEquals(array(), $queue->peek(0, 10)); + $this->assertEquals([], $queue->peek(0, 10)); - $queue->enqueue($envelope = $this->getEnvelope()); + $queue->enqueue($envelope = $this->getEnvelope()); $queue->enqueue($envelope1 = $this->getEnvelope()); $queue->enqueue($envelope2 = $this->getEnvelope()); $queue->enqueue($envelope3 = $this->getEnvelope()); $this->assertCount(4, $queue); - $this->assertSame(array( + $this->assertSame([ $envelope1, $envelope2, - ), $queue->peek(1, 2)); + ], $queue->peek(1, 2)); $this->assertCount(4, $queue); } diff --git a/tests/Queue/PersistentQueueTest.php b/tests/Queue/PersistentQueueTest.php index 877f2455..de3f1bd9 100644 --- a/tests/Queue/PersistentQueueTest.php +++ b/tests/Queue/PersistentQueueTest.php @@ -34,7 +34,7 @@ public function testAcknowledge() ->with($this->equalTo('send-newsletter'), $this->equalTo('receipt')); $this->driver->expects($this->once())->method('popMessage')->with($this->equalTo('send-newsletter')) - ->will($this->returnValue(array('message', 'receipt'))); + ->will($this->returnValue(['message', 'receipt'])); $this->serializer->expects($this->once())->method('unserialize') ->will($this->returnValue($envelope)); @@ -69,7 +69,7 @@ public function testDequeue() $messageWrapper = new Envelope($this->createMock('Bernard\Message')); $this->driver->expects($this->at(1))->method('popMessage')->with($this->equalTo('send-newsletter')) - ->will($this->returnValue(array('serialized', null))); + ->will($this->returnValue(['serialized', null])); $this->driver->expects($this->at(2))->method('popMessage')->with($this->equalTo('send-newsletter')) ->will($this->returnValue(null)); @@ -93,7 +93,7 @@ public function testPeekDserializesMessages($index, $limit) $this->serializer->expects($this->at(2))->method('unserialize')->with($this->equalTo('message3')); $this->driver->expects($this->once())->method('peekQueue')->with($this->equalTo('send-newsletter'), $this->equalTo($index), $this->equalTo($limit)) - ->will($this->returnValue(array('message1', 'message2', 'message3'))); + ->will($this->returnValue(['message1', 'message2', 'message3'])); $queue = $this->createQueue('send-newsletter'); $queue->peek($index, $limit); @@ -102,18 +102,18 @@ public function testPeekDserializesMessages($index, $limit) public function dataClosedMethods() { $methods = parent::dataClosedMethods(); - $methods[] = array('register', array()); + $methods[] = ['register', []]; return $methods; } public function peekDataProvider() { - return array( - array(0, 20), - array(1, 10), - array(20, 100), - ); + return [ + [0, 20], + [1, 10], + [20, 100], + ]; } protected function createQueue($name) diff --git a/tests/Queue/RoundRobinQueueTest.php b/tests/Queue/RoundRobinQueueTest.php index c2bb6eff..7eabf0aa 100644 --- a/tests/Queue/RoundRobinQueueTest.php +++ b/tests/Queue/RoundRobinQueueTest.php @@ -69,7 +69,7 @@ public function testClose() { $builder = $this->getMockBuilder('Bernard\\Queue\\InMemoryQueue')->setMethods(['close']); $queues = []; - for ($name = 1; $name <= 3; $name++) { + for ($name = 1; $name <= 3; ++$name) { $queue = $builder->setConstructorArgs([$name])->getMock(); $queue ->expects($this->once()) diff --git a/tests/QueueFactory/PersistentFactoryTest.php b/tests/QueueFactory/PersistentFactoryTest.php index 4b3fb9fc..2a3b01c2 100644 --- a/tests/QueueFactory/PersistentFactoryTest.php +++ b/tests/QueueFactory/PersistentFactoryTest.php @@ -54,7 +54,7 @@ public function testItLazyCreatesQueuesAndAttaches() public function testItsCountable() { $this->connection->expects($this->once())->method('listQueues') - ->will($this->returnValue(array('failed', 'something', 'queue-ness'))); + ->will($this->returnValue(['failed', 'something', 'queue-ness'])); $this->assertCount(3, $this->factory); } @@ -62,7 +62,7 @@ public function testItsCountable() public function testItGetsAllQueues() { $this->connection->expects($this->once())->method('listQueues') - ->will($this->returnValue(array('queue1', 'queue2'))); + ->will($this->returnValue(['queue1', 'queue2'])); $all = $this->factory->all(); diff --git a/tests/Router/ContainerAwareRouterTest.php b/tests/Router/ContainerAwareRouterTest.php index 3a6243fb..8da8bb7d 100644 --- a/tests/Router/ContainerAwareRouterTest.php +++ b/tests/Router/ContainerAwareRouterTest.php @@ -11,7 +11,7 @@ class ContainerAwareRouterTest extends \PHPUnit\Framework\TestCase { public function setUp() { - $this->container = new Container; + $this->container = new Container(); $this->container->set('my.service', function () { return 'var_dump'; }); @@ -30,7 +30,7 @@ public function testUndefinedServicesAreNotAccepted() public function testAcceptsInConstructor() { - $router = new ContainerAwareRouter($this->container, array('SendNewsletter' => 'my.service')); + $router = new ContainerAwareRouter($this->container, ['SendNewsletter' => 'my.service']); $envelope = new Envelope(new PlainMessage('SendNewsletter')); $this->assertSame($this->container->get('my.service'), $router->map($envelope)); @@ -40,9 +40,9 @@ public function testAcceptsContainerServiceAsReceiver() { $envelope = new Envelope(new PlainMessage('SendNewsletter')); - $router = new ContainerAwareRouter($this->container, array( + $router = new ContainerAwareRouter($this->container, [ 'SendNewsletter' => 'my.service', - )); + ]); $this->assertSame($this->container->get('my.service'), $router->map($envelope)); } diff --git a/tests/Router/LeagueContainerAwareRouterTest.php b/tests/Router/LeagueContainerAwareRouterTest.php index 30ad101d..23e446c8 100644 --- a/tests/Router/LeagueContainerAwareRouterTest.php +++ b/tests/Router/LeagueContainerAwareRouterTest.php @@ -11,7 +11,7 @@ class LeagueContainerAwareRouterTest extends \PHPUnit\Framework\TestCase { public function setUp() { - $this->container = new Container; + $this->container = new Container(); $this->container->add('my.service', function () { return 'var_dump'; }); @@ -30,7 +30,7 @@ public function testUndefinedServicesAreNotAccepted() public function testAcceptsInConstructor() { - $router = new LeagueContainerAwareRouter($this->container, array('SendNewsletter' => 'my.service')); + $router = new LeagueContainerAwareRouter($this->container, ['SendNewsletter' => 'my.service']); $envelope = new Envelope(new PlainMessage('SendNewsletter')); $this->assertSame($this->container->get('my.service'), $router->map($envelope)); diff --git a/tests/Router/PimpleAwareRouterTest.php b/tests/Router/PimpleAwareRouterTest.php index 889d24ea..b43757df 100644 --- a/tests/Router/PimpleAwareRouterTest.php +++ b/tests/Router/PimpleAwareRouterTest.php @@ -11,7 +11,7 @@ class PimpleAwareRouterTest extends \PHPUnit\Framework\TestCase { public function setUp() { - $this->pimple = new Pimple; + $this->pimple = new Pimple(); $this->pimple['my.service'] = $this->pimple->share(function () { return 'var_dump'; }); @@ -31,7 +31,7 @@ public function testUndefinedServicesAreNotAccepted() public function testAcceptsInConstructor() { - $router = new PimpleAwareRouter($this->pimple, array('SendNewsletter' => 'my.service')); + $router = new PimpleAwareRouter($this->pimple, ['SendNewsletter' => 'my.service']); $envelope = new Envelope(new PlainMessage('SendNewsletter')); $this->assertSame($this->pimple['my.service'], $router->map($envelope)); diff --git a/tests/Router/SimpleRouterTest.php b/tests/Router/SimpleRouterTest.php index 04e677d9..533a4325 100644 --- a/tests/Router/SimpleRouterTest.php +++ b/tests/Router/SimpleRouterTest.php @@ -36,9 +36,9 @@ public function testReceiversAreAddedThroughConstructor() $callable = function () {}; $envelope = new Envelope(new PlainMessage('SendNewsletter')); - $router = new SimpleRouter(array( + $router = new SimpleRouter([ 'SendNewsletter' => $callable, - )); + ]); $this->assertSame($callable, $router->map($envelope)); } @@ -59,11 +59,11 @@ public function provideCallable() { $callable = function () {}; - return array( - array('Bernard\Tests\Fixtures\Service', array('Bernard\Tests\Fixtures\Service', 'sendNewsletter')), - array('var_dump', 'var_dump'), - array($callable, $callable), - array(new \stdClass, array(new \stdClass, 'sendNewsletter')) - ); + return [ + ['Bernard\Tests\Fixtures\Service', ['Bernard\Tests\Fixtures\Service', 'sendNewsletter']], + ['var_dump', 'var_dump'], + [$callable, $callable], + [new \stdClass(), [new \stdClass(), 'sendNewsletter']], + ]; } } From ea91a0b339807744d7514b7e95e82b6525144af4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Wed, 14 Feb 2018 14:56:47 +0100 Subject: [PATCH 010/108] Fix typo --- doc/drivers.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/drivers.rst b/doc/drivers.rst index 7ccbc99b..a01655a1 100644 --- a/doc/drivers.rst +++ b/doc/drivers.rst @@ -106,7 +106,7 @@ as appropriate for your use case. Date: Thu, 15 Feb 2018 06:25:37 +0100 Subject: [PATCH 011/108] Improve readme Fixes #358 --- README.md | 46 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 3cf7a9b5..efe60950 100644 --- a/README.md +++ b/README.md @@ -4,23 +4,41 @@

-Bernard makes it super easy and enjoyable to do background processing in PHP. It does this by utilizing queues and long running processes. It supports normal queueing drivers but also implements simple ones with Redis and Doctrine. +[![Latest Version](https://img.shields.io/github/release/bernardphp/bernard.svg?style=flat-square)](https://github.com/bernardphp/bernard/releases) +[![Build Status](https://img.shields.io/travis/bernardphp/bernard.svg?style=flat-square)](https://travis-ci.org/bernardphp/bernard) +[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/bernardphp/bernard.svg?style=flat-square)](https://scrutinizer-ci.com/g/bernardphp/bernard) +[![Quality Score](https://img.shields.io/scrutinizer/g/bernardphp/bernard.svg?style=flat-square)](https://scrutinizer-ci.com/g/bernardphp/bernard) +[![Total Downloads](https://img.shields.io/packagist/dt/bernard/bernard.svg?style=flat-square)](https://packagist.org/packages/bernard/bernard) + +Bernard makes it super easy and enjoyable to do background processing in PHP. +It does this by utilizing queues and long running processes. +It supports normal queueing drivers but also implements simple ones with Redis and Doctrine. Currently these are the supported backends, with more coming with each release: - * Predis / PhpRedis - * Amazon SQS - * Iron MQ - * Doctrine DBAL - * Pheanstalk - * PhpAmqp / RabbitMQ - * Queue interop +- Predis / PhpRedis +- Amazon SQS +- Iron MQ +- Doctrine DBAL +- Pheanstalk +- PhpAmqp / RabbitMQ +- Queue interop + + +## Install + +Via Composer + +```bash +$ composer require bernard/bernard +``` + + +## Documentation + +Please see the [official documentation](https://bernard.readthedocs.org). -You can learn more on our website about Bernard and its [related projects][website] or just dive directly into [the -documentation][documentation]. -[![Build Status](https://travis-ci.org/bernardphp/bernard.png?branch=master)][travis] [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/bernardphp/bernard/badges/quality-score.png?s=f752c78d347624081f5b6d3d818fe14eef0311c2)](https://scrutinizer-ci.com/g/bernardphp/bernard/) +## License -[documentation]: https://bernard.readthedocs.org -[website]: http://bernardphp-com.rtfd.org -[travis]: https://travis-ci.org/bernardphp/bernard +The MIT License (MIT). Please see [License File](LICENSE) for more information. From cc27d05d993501667a8c135aad6742d627084558 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 06:30:18 +0100 Subject: [PATCH 012/108] Remove HHVM build HHVM is not going to follow PHP, so it makes no sense to keep building it. --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 153ea7ea..5c823e33 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,7 +6,6 @@ language: php php: - 5.6 - 7.0 - - hhvm env: - COMPOSER_OPTS="" From 58344337d77700020e73035978b89d96ea69dbfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 06:31:19 +0100 Subject: [PATCH 013/108] Add builds for PHP 7.x --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index 5c823e33..1ae659f9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,6 +6,8 @@ language: php php: - 5.6 - 7.0 + - 7.1 + - 7.2 env: - COMPOSER_OPTS="" From 366faa05584085a27984ccf7795859b6617953d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 07:10:44 +0100 Subject: [PATCH 014/108] Improve CI and testing --- .editorconfig | 20 ++------ .gitattributes | 18 ++++--- .scrutinizer.yml | 9 ++++ .travis.yml | 48 ++++++++++++++----- README.md | 15 ++++++ composer.json | 17 +++++-- phpspec.ci.yml | 10 ++++ phpspec.yml.dist | 5 ++ .../Normalizer/EnvelopeNormalizerSpec.php | 21 ++------ .../Router/ClassNameRouterSpec.php | 0 spec/{Bernard => }/SerializerSpec.php | 18 +++---- tests/travis.sh | 21 -------- 12 files changed, 115 insertions(+), 87 deletions(-) create mode 100644 .scrutinizer.yml create mode 100644 phpspec.ci.yml create mode 100644 phpspec.yml.dist rename spec/{Bernard => }/Normalizer/EnvelopeNormalizerSpec.php (83%) rename spec/{Bernard => }/Router/ClassNameRouterSpec.php (100%) rename spec/{Bernard => }/SerializerSpec.php (75%) delete mode 100755 tests/travis.sh diff --git a/.editorconfig b/.editorconfig index 5d24621f..677e36e2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,23 +1,9 @@ root = true [*] -end_of_line = lf charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true - -[composer.json] -indent_style = space -indent_size = 4 - -[*.php] -indent_style = space +end_of_line = lf indent_size = 4 - -[*.yml] indent_style = space -indent_size = 2 - -[phpspec.*] -indent_style = space -indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true diff --git a/.gitattributes b/.gitattributes index 2cad7e1c..2b7564bf 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,7 +1,11 @@ -/tests export-ignore -/doc export-ignore -.gitattributes export-ignore -.gitignore export-ignore -.editorconfig export-ignore -.travis.yml export-ignore -phpunit.xml.dist export-ignore +/doc/ export-ignore +/spec/ export-ignore +/tests/ export-ignore +/.editorconfig export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/.php_cs.dist export-ignore +/.travis.yml export-ignore +/phpspec.ci.yml export-ignore +/phpspec.yml.dist export-ignore +/phpunit.xml.dist export-ignore diff --git a/.scrutinizer.yml b/.scrutinizer.yml new file mode 100644 index 00000000..a5f975ba --- /dev/null +++ b/.scrutinizer.yml @@ -0,0 +1,9 @@ +filter: + paths: [src/*] +checks: + php: + code_rating: true + duplication: true +tools: + external_code_coverage: + runs: 2 diff --git a/.travis.yml b/.travis.yml index 1ae659f9..2ae645b5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,12 @@ -sudo: false +language: php + dist: trusty -language: php +sudo: false +cache: + directories: + - $HOME/.composer/cache/files php: - 5.6 - 7.0 @@ -10,22 +14,44 @@ php: - 7.2 env: - - COMPOSER_OPTS="" - - COMPOSER_OPTS="--prefer-lowest" + global: + - TEST_COMMAND="composer test" -cache: - directories: - - $HOME/.composer/cache/files +matrix: + fast_finish: true + include: + - php: 5.6 + env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest" COVERAGE=true TEST_COMMAND="composer test-ci" services: - mongodb - mysql - postgresql +before_install: + - if [[ $COVERAGE != true ]]; then phpenv config-rm xdebug.ini || true; fi + - echo "extension=redis.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini + - export MONGOEXT="mongodb" + - if [[ $TRAVIS_PHP_VERSION = "5.6" ]]; then export MONGOEXT="mongo"; fi + - echo "extension=$MONGOEXT.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini + +install: + # To be removed when this issue will be resolved: https://github.com/composer/composer/issues/5355 + - if [[ "$COMPOSER_FLAGS" == *"--prefer-lowest"* ]]; then travis_retry composer update --prefer-dist --no-interaction --prefer-stable --quiet; fi + - travis_retry composer update ${COMPOSER_FLAGS} --prefer-dist --no-interaction + before_script: - - tests/travis.sh + - mysql -e "CREATE DATABASE bernard_test;" + - psql -c 'CREATE DATABASE bernard_test;' -U postgres script: - - php vendor/bin/phpunit -v - - php vendor/bin/phpunit --group functional -v - - php vendor/bin/phpspec run + - $TEST_COMMAND + - composer test-functional + +after_success: > + if [[ $COVERAGE = true ]]; then + wget https://scrutinizer-ci.com/ocular.phar + + php ocular.phar code-coverage:upload --format=php-clover build/spec_coverage.xml + php ocular.phar code-coverage:upload --format=php-clover build/unit_coverage.xml + fi diff --git a/README.md b/README.md index efe60950..6254d23a 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,21 @@ $ composer require bernard/bernard Please see the [official documentation](https://bernard.readthedocs.org). +## Testing + +We try to follow BDD and TDD, as such we use both [phpspec](http://www.phpspec.net) and [phpunit](https://phpunit.de) to test this library. + +```bash +$ composer test +``` + +You can run the functional tests by executing: + +```bash +$ composer test-functional +``` + + ## License The MIT License (MIT). Please see [License File](LICENSE) for more information. diff --git a/composer.json b/composer.json index 1719e49a..3cedb760 100644 --- a/composer.json +++ b/composer.json @@ -22,8 +22,9 @@ "aws/aws-sdk-php": "~2.4|~3.0", "pda/pheanstalk": "~3.0", "php-amqplib/php-amqplib": "~2.5", - "phpspec/phpspec": "^2.4", - "phpunit/phpunit": "^5.5|^6.0", + "phpspec/phpspec": "^3.0 || ^4.0", + "henrikbjorn/phpspec-code-coverage": "^3.0", + "phpunit/phpunit": "^5.5 || ^6.0 || ^7.0", "iron-io/iron_mq": "~4.0", "league/container": "~2.3", "queue-interop/queue-interop": "^0.6", @@ -47,7 +48,17 @@ "autoload-dev" : { "psr-4" : { "Bernard\\Tests\\" : "tests/" } }, - + "scripts": { + "test": [ + "vendor/bin/phpspec run", + "vendor/bin/phpunit -v" + ], + "test-ci": [ + "vendor/bin/phpspec run -c phpspec.ci.yml", + "vendor/bin/phpunit -v --coverage-text --coverage-clover=build/unit_coverage.xml" + ], + "test-functional": "php vendor/bin/phpunit -v --group functional" + }, "extra" : { "branch-alias" : { "dev-master" : "1.0.x-dev" diff --git a/phpspec.ci.yml b/phpspec.ci.yml new file mode 100644 index 00000000..6e4bfe75 --- /dev/null +++ b/phpspec.ci.yml @@ -0,0 +1,10 @@ +suites: + bernard_suite: + namespace: Bernard + psr4_prefix: Bernard +formatter.name: pretty +extensions: + - PhpSpec\Extension\CodeCoverageExtension +code_coverage: + format: clover + output: build/spec_coverage.xml diff --git a/phpspec.yml.dist b/phpspec.yml.dist new file mode 100644 index 00000000..a82bebf6 --- /dev/null +++ b/phpspec.yml.dist @@ -0,0 +1,5 @@ +suites: + bernard_suite: + namespace: Bernard + psr4_prefix: Bernard +formatter.name: pretty diff --git a/spec/Bernard/Normalizer/EnvelopeNormalizerSpec.php b/spec/Normalizer/EnvelopeNormalizerSpec.php similarity index 83% rename from spec/Bernard/Normalizer/EnvelopeNormalizerSpec.php rename to spec/Normalizer/EnvelopeNormalizerSpec.php index e2e26c7b..e8669e87 100644 --- a/spec/Bernard/Normalizer/EnvelopeNormalizerSpec.php +++ b/spec/Normalizer/EnvelopeNormalizerSpec.php @@ -2,29 +2,21 @@ namespace spec\Bernard\Normalizer; +use Bernard\Envelope; +use Bernard\Message; +use Normalt\Normalizer\AggregateNormalizer; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class EnvelopeNormalizerSpec extends ObjectBehavior { - /** - * @param Normalt\Normalizer\AggregateNormalizer $aggregate - */ - function let($aggregate) - { - } - function it_is_a_normalizer_and_denormailzer() { $this->shouldHaveType('Symfony\Component\Serializer\Normalizer\NormalizerInterface'); $this->shouldHaveType('Symfony\Component\Serializer\Normalizer\DenormalizerInterface'); } - /** - * @param Bernard\Envelope $envelope - * @param Bernard\Message $message - */ - function it_normalizes_envelope_and_delegates_message_to_aggregate($envelope, $message, $aggregate) + function it_normalizes_envelope_and_delegates_message_to_aggregate(Envelope $envelope, Message $message, AggregateNormalizer $aggregate) { $envelope->getMessage()->willReturn($message); $envelope->getClass()->willReturn('Bernard\Message\PlainMessage'); @@ -43,10 +35,7 @@ function it_normalizes_envelope_and_delegates_message_to_aggregate($envelope, $m )); } - /** - * @param Bernard\Message $message - */ - function it_denormalizes_envelope_and_delegates_message_to_aggregate($message, $aggregate) + function it_denormalizes_envelope_and_delegates_message_to_aggregate(Message $message, AggregateNormalizer $aggregate) { $this->setAggregateNormalizer($aggregate); diff --git a/spec/Bernard/Router/ClassNameRouterSpec.php b/spec/Router/ClassNameRouterSpec.php similarity index 100% rename from spec/Bernard/Router/ClassNameRouterSpec.php rename to spec/Router/ClassNameRouterSpec.php diff --git a/spec/Bernard/SerializerSpec.php b/spec/SerializerSpec.php similarity index 75% rename from spec/Bernard/SerializerSpec.php rename to spec/SerializerSpec.php index 4ac5fc3c..5a7462dd 100644 --- a/spec/Bernard/SerializerSpec.php +++ b/spec/SerializerSpec.php @@ -2,20 +2,17 @@ namespace spec\Bernard; +use Bernard\Envelope; +use Normalt\Normalizer\AggregateNormalizer; + class SerializerSpec extends \PhpSpec\ObjectBehavior { - /** - * @param Normalt\Normalizer\AggregateNormalizer $aggregate - */ - function let($aggregate) + function let(AggregateNormalizer $aggregate) { $this->beConstructedWith($aggregate); } - /** - * @param Bernard\Envelope $envelope - */ - function it_serializes_normalized_envelope_into_json($envelope, $aggregate) + function it_serializes_normalized_envelope_into_json(Envelope $envelope, AggregateNormalizer $aggregate) { $aggregate->normalize($envelope, null)->willReturn(array( 'class' => 'Bernard\\Message\\PlainMessage', @@ -27,10 +24,7 @@ function it_serializes_normalized_envelope_into_json($envelope, $aggregate) ->shouldReturn('{"class":"Bernard\\\\Message\\\\PlainMessage","timestamp":1337,"message":{"name":"Import","arguments":{"arg1":"value"}}}'); } - /** - * @param Bernard\Envelope $envelope - */ - function it_unserializes_into_envelope($envelope, $aggregate) + function it_unserializes_into_envelope(Envelope $envelope, AggregateNormalizer $aggregate) { $normalized = array( 'class' => 'Bernard\\Message\\PlainMessage', diff --git a/tests/travis.sh b/tests/travis.sh deleted file mode 100755 index 81fcb231..00000000 --- a/tests/travis.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash - -if [ $TRAVIS_PHP_VERSION != "hhvm" ] && [ $TRAVIS_PHP_VERSION != "7.0" ]; then - echo "extension=mongo.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; -fi - -if [ $TRAVIS_PHP_VERSION != "hhvm" ] && [ $TRAVIS_PHP_VERSION != "5.6" ]; then - echo "extension=mongodb.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; -fi - -if [ $TRAVIS_PHP_VERSION = "hhvm" ]; then - composer require --dev mongofill/mongofill=dev-master --no-update; - composer update --no-progress --no-plugins; -else - phpenv config-rm xdebug.ini; - composer update --no-progress --no-plugins $COMPOSER_OPTS; - echo "extension=redis.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; -fi - -mysql -e "CREATE DATABASE bernard_test;" -psql -c 'CREATE DATABASE bernard_test;' -U postgres From 1750e722916790efd8f241be42117201588036b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 07:16:11 +0100 Subject: [PATCH 015/108] Improve existing specs --- spec/Normalizer/EnvelopeNormalizerSpec.php | 37 +++++++++++----------- spec/Router/ClassNameRouterSpec.php | 16 ++++++---- spec/SerializerSpec.php | 19 +++++------ 3 files changed, 39 insertions(+), 33 deletions(-) diff --git a/spec/Normalizer/EnvelopeNormalizerSpec.php b/spec/Normalizer/EnvelopeNormalizerSpec.php index e8669e87..b0cbc273 100644 --- a/spec/Normalizer/EnvelopeNormalizerSpec.php +++ b/spec/Normalizer/EnvelopeNormalizerSpec.php @@ -6,51 +6,52 @@ use Bernard\Message; use Normalt\Normalizer\AggregateNormalizer; use PhpSpec\ObjectBehavior; -use Prophecy\Argument; +use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; class EnvelopeNormalizerSpec extends ObjectBehavior { function it_is_a_normalizer_and_denormailzer() { - $this->shouldHaveType('Symfony\Component\Serializer\Normalizer\NormalizerInterface'); - $this->shouldHaveType('Symfony\Component\Serializer\Normalizer\DenormalizerInterface'); + $this->shouldImplement(NormalizerInterface::class); + $this->shouldImplement(DenormalizerInterface::class); } function it_normalizes_envelope_and_delegates_message_to_aggregate(Envelope $envelope, Message $message, AggregateNormalizer $aggregate) { $envelope->getMessage()->willReturn($message); - $envelope->getClass()->willReturn('Bernard\Message\PlainMessage'); + $envelope->getClass()->willReturn(Message\PlainMessage::class); $envelope->getTimestamp()->willReturn(1337); - $aggregate->normalize($message)->willReturn(array( + $aggregate->normalize($message)->willReturn([ 'key' => 'value', - )); + ]); $this->setAggregateNormalizer($aggregate); - $this->normalize($envelope)->shouldReturn(array( - 'class' => 'Bernard\\Message\\PlainMessage', + $this->normalize($envelope)->shouldReturn([ + 'class' => Message\PlainMessage::class, 'timestamp' => 1337, - 'message' => array('key' => 'value'), - )); + 'message' => ['key' => 'value'], + ]); } function it_denormalizes_envelope_and_delegates_message_to_aggregate(Message $message, AggregateNormalizer $aggregate) { $this->setAggregateNormalizer($aggregate); - $aggregate->denormalize(array('key' => 'value'), 'Bernard\\Message\\PlainMessage', null)->willReturn($message); + $aggregate->denormalize(['key' => 'value'], Message\PlainMessage::class, null)->willReturn($message); - $normalized = array( - 'class' => 'Bernard\\Message\\PlainMessage', + $normalized = [ + 'class' => Message\PlainMessage::class, 'timestamp' => 1337, - 'message' => array('key' => 'value'), - ); + 'message' => ['key' => 'value'], + ]; - $envelope = $this->denormalize($normalized, 'Bernard\\Envelope'); - $envelope->shouldHaveType('Bernard\\Envelope'); + $envelope = $this->denormalize($normalized, Envelope::class); + $envelope->shouldHaveType(Envelope::class); $envelope->getMessage()->shouldReturn($message); $envelope->getTimestamp()->shouldReturn(1337); - $envelope->getClass()->shouldReturn('Bernard\\Message\\PlainMessage'); + $envelope->getClass()->shouldReturn(Message\PlainMessage::class); } } diff --git a/spec/Router/ClassNameRouterSpec.php b/spec/Router/ClassNameRouterSpec.php index 298700ee..f4961936 100644 --- a/spec/Router/ClassNameRouterSpec.php +++ b/spec/Router/ClassNameRouterSpec.php @@ -3,6 +3,10 @@ namespace spec\Bernard\Router; use Bernard\Envelope; +use Bernard\Exception\ReceiverNotFoundException; +use Bernard\Message; +use Bernard\Router; +use Bernard\Router\ClassNameRouter; use PhpSpec\ObjectBehavior; class ClassNameRouterSpec extends ObjectBehavior @@ -10,31 +14,31 @@ class ClassNameRouterSpec extends ObjectBehavior function let() { $this->beConstructedWith([ - 'Bernard\\Message' => function() {}, + Message::class => function() {}, ]); } function it_is_initializable() { - $this->shouldHaveType('Bernard\\Router\\ClassNameRouter'); + $this->shouldHaveType(ClassNameRouter::class); } function it_is_a_router() { - $this->shouldImplement('Bernard\\Router'); + $this->shouldImplement(Router::class); } function it_maps_an_envelope(Envelope $envelope) { - $envelope->getClass()->willReturn('Bernard\\Message\\DefaultMessage'); + $envelope->getClass()->willReturn(Message\PlainMessage::class); $this->map($envelope)->shouldBeCallable(); } function it_throws_an_exception_when_envelope_cannot_be_mapped(Envelope $envelope) { - $envelope->getClass()->willReturn('Bernard\\Producer'); + $envelope->getClass()->willReturn(\stdClass::class); - $this->shouldThrow('Bernard\\Exception\\ReceiverNotFoundException')->duringMap($envelope); + $this->shouldThrow(ReceiverNotFoundException::class)->duringMap($envelope); } } diff --git a/spec/SerializerSpec.php b/spec/SerializerSpec.php index 5a7462dd..b56d6878 100644 --- a/spec/SerializerSpec.php +++ b/spec/SerializerSpec.php @@ -3,6 +3,7 @@ namespace spec\Bernard; use Bernard\Envelope; +use Bernard\Message\PlainMessage; use Normalt\Normalizer\AggregateNormalizer; class SerializerSpec extends \PhpSpec\ObjectBehavior @@ -14,11 +15,11 @@ function let(AggregateNormalizer $aggregate) function it_serializes_normalized_envelope_into_json(Envelope $envelope, AggregateNormalizer $aggregate) { - $aggregate->normalize($envelope, null)->willReturn(array( - 'class' => 'Bernard\\Message\\PlainMessage', + $aggregate->normalize($envelope, null)->willReturn([ + 'class' => PlainMessage::class, 'timestamp' => 1337, - 'message' => array('name' => 'Import', 'arguments' => array('arg1' => 'value')), - )); + 'message' => ['name' => 'Import', 'arguments' => ['arg1' => 'value']], + ]); $this->serialize($envelope) ->shouldReturn('{"class":"Bernard\\\\Message\\\\PlainMessage","timestamp":1337,"message":{"name":"Import","arguments":{"arg1":"value"}}}'); @@ -26,13 +27,13 @@ function it_serializes_normalized_envelope_into_json(Envelope $envelope, Aggrega function it_unserializes_into_envelope(Envelope $envelope, AggregateNormalizer $aggregate) { - $normalized = array( - 'class' => 'Bernard\\Message\\PlainMessage', + $normalized = [ + 'class' => PlainMessage::class, 'timestamp' => 1337, - 'message' => array('name' => 'Import', 'arguments' => array('arg1' => 'value')), - ); + 'message' => ['name' => 'Import', 'arguments' => ['arg1' => 'value']], + ]; - $aggregate->denormalize($normalized, 'Bernard\Envelope', null)->willReturn($envelope); + $aggregate->denormalize($normalized, Envelope::class, null)->willReturn($envelope); $this->unserialize('{"class":"Bernard\\\\Message\\\\PlainMessage","timestamp":1337,"message":{"name":"Import","arguments":{"arg1":"value"}}}') ->shouldReturn($envelope); From d507c527ece380fed8322a323b3bef3ed0620910 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 07:25:47 +0100 Subject: [PATCH 016/108] Fix PHP 7.2 count issues Fixes #353 --- src/Command/ConsumeCommand.php | 10 +++++----- src/QueueFactory/InMemoryFactory.php | 2 +- tests/QueueFactory/PersistentFactoryTest.php | 3 +++ 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/Command/ConsumeCommand.php b/src/Command/ConsumeCommand.php index 60046eeb..77696c21 100644 --- a/src/Command/ConsumeCommand.php +++ b/src/Command/ConsumeCommand.php @@ -59,13 +59,13 @@ public function execute(InputInterface $input, OutputInterface $output) */ protected function getQueue($queue) { - if (count($queue) > 1) { - $queues = array_map([$this->queues, 'create'], $queue); + if (is_array($queue)) { + if (count($queue) > 1) { + $queues = array_map([$this->queues, 'create'], $queue); - return new RoundRobinQueue($queues); - } + return new RoundRobinQueue($queues); + } - if (is_array($queue)) { $queue = $queue[0]; } diff --git a/src/QueueFactory/InMemoryFactory.php b/src/QueueFactory/InMemoryFactory.php index 8e3bc7bd..6f171342 100644 --- a/src/QueueFactory/InMemoryFactory.php +++ b/src/QueueFactory/InMemoryFactory.php @@ -10,7 +10,7 @@ */ class InMemoryFactory implements \Bernard\QueueFactory { - protected $queues; + protected $queues = []; /** * {@inheritdoc} diff --git a/tests/QueueFactory/PersistentFactoryTest.php b/tests/QueueFactory/PersistentFactoryTest.php index 2a3b01c2..126cc0c3 100644 --- a/tests/QueueFactory/PersistentFactoryTest.php +++ b/tests/QueueFactory/PersistentFactoryTest.php @@ -34,6 +34,9 @@ public function testItSavesQueueObjects() */ public function testRemoveClosesQueue() { + $this->connection->expects($this->once())->method('listQueues') + ->will($this->returnValue([])); + $queue = $this->factory->create('send-newsletter'); $this->assertTrue($this->factory->exists('send-newsletter')); From 3dcc74dbef6723ea763f574c2ab7ef4b18d91f42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 07:33:51 +0100 Subject: [PATCH 017/108] Fix phpspec --- phpspec.ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpspec.ci.yml b/phpspec.ci.yml index 6e4bfe75..59d5d6ce 100644 --- a/phpspec.ci.yml +++ b/phpspec.ci.yml @@ -4,7 +4,7 @@ suites: psr4_prefix: Bernard formatter.name: pretty extensions: - - PhpSpec\Extension\CodeCoverageExtension + PhpSpec\Extension\CodeCoverageExtension: ~ code_coverage: format: clover output: build/spec_coverage.xml From 2ed6c4f631c86a71896dddc9f9180746d5851d6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 07:39:13 +0100 Subject: [PATCH 018/108] Fix spec coverage --- composer.json | 2 +- phpspec.ci.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 3cedb760..0c27ea26 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,7 @@ "pda/pheanstalk": "~3.0", "php-amqplib/php-amqplib": "~2.5", "phpspec/phpspec": "^3.0 || ^4.0", - "henrikbjorn/phpspec-code-coverage": "^3.0", + "leanphp/phpspec-code-coverage": "^3.0 || ^4.0", "phpunit/phpunit": "^5.5 || ^6.0 || ^7.0", "iron-io/iron_mq": "~4.0", "league/container": "~2.3", diff --git a/phpspec.ci.yml b/phpspec.ci.yml index 59d5d6ce..16997c54 100644 --- a/phpspec.ci.yml +++ b/phpspec.ci.yml @@ -4,7 +4,7 @@ suites: psr4_prefix: Bernard formatter.name: pretty extensions: - PhpSpec\Extension\CodeCoverageExtension: ~ + LeanPHP\PhpSpec\CodeCoverage\CodeCoverageExtension: ~ code_coverage: format: clover output: build/spec_coverage.xml From 0b9b1b428955003ac58bb9318c408480f828aeb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 07:47:13 +0100 Subject: [PATCH 019/108] Fix phpspec config --- phpspec.ci.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/phpspec.ci.yml b/phpspec.ci.yml index 16997c54..b5263b2a 100644 --- a/phpspec.ci.yml +++ b/phpspec.ci.yml @@ -4,7 +4,8 @@ suites: psr4_prefix: Bernard formatter.name: pretty extensions: - LeanPHP\PhpSpec\CodeCoverage\CodeCoverageExtension: ~ -code_coverage: - format: clover - output: build/spec_coverage.xml + LeanPHP\PhpSpec\CodeCoverage\CodeCoverageExtension: + format: + - clover + output: + clover: build/spec_coverage.xml From f9b38c9cc5be3b4f75261303e6f37454f721794d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 07:56:15 +0100 Subject: [PATCH 020/108] Remove deprecated DefaultMessage Fixes #361 --- src/Message/DefaultMessage.php | 12 ------------ tests/EventListener/FailureSubscriberTest.php | 4 ++-- tests/Message/DefaultMessageTest.php | 13 ------------- 3 files changed, 2 insertions(+), 27 deletions(-) delete mode 100644 src/Message/DefaultMessage.php delete mode 100644 tests/Message/DefaultMessageTest.php diff --git a/src/Message/DefaultMessage.php b/src/Message/DefaultMessage.php deleted file mode 100644 index d7240199..00000000 --- a/src/Message/DefaultMessage.php +++ /dev/null @@ -1,12 +0,0 @@ -producer->expects($this->once()) ->method('produce') diff --git a/tests/Message/DefaultMessageTest.php b/tests/Message/DefaultMessageTest.php deleted file mode 100644 index 49afdb1d..00000000 --- a/tests/Message/DefaultMessageTest.php +++ /dev/null @@ -1,13 +0,0 @@ - Date: Thu, 15 Feb 2018 08:36:52 +0100 Subject: [PATCH 021/108] Replace the abstract message with traits, closes #362 --- .../{AbstractMessage.php => HasName.php} | 16 ++++--------- src/Message/HasQueue.php | 24 +++++++++++++++++++ src/Message/PlainMessage.php | 3 ++- tests/Fixtures/SendNewsletterMessage.php | 6 +++-- tests/Message/AbstractMessageTest.php | 21 ---------------- 5 files changed, 34 insertions(+), 36 deletions(-) rename src/Message/{AbstractMessage.php => HasName.php} (60%) create mode 100644 src/Message/HasQueue.php delete mode 100644 tests/Message/AbstractMessageTest.php diff --git a/src/Message/AbstractMessage.php b/src/Message/HasName.php similarity index 60% rename from src/Message/AbstractMessage.php rename to src/Message/HasName.php index fc2dfc65..cb0407ab 100644 --- a/src/Message/AbstractMessage.php +++ b/src/Message/HasName.php @@ -2,10 +2,10 @@ namespace Bernard\Message; -use Bernard\Message; -use Bernard\Util; - -abstract class AbstractMessage implements Message +/** + * Apply this trait to your message when you want it to follow the default message naming pattern. + */ +trait HasName { /** * {@inheritdoc} @@ -20,12 +20,4 @@ public function getName() return current(array_reverse(explode('\\', $class))); } - - /** - * {@inheritdoc} - */ - public function getQueue() - { - return Util::guessQueue($this); - } } diff --git a/src/Message/HasQueue.php b/src/Message/HasQueue.php new file mode 100644 index 00000000..e4b63f8b --- /dev/null +++ b/src/Message/HasQueue.php @@ -0,0 +1,24 @@ +getName())), '-'); + } +} diff --git a/src/Message/PlainMessage.php b/src/Message/PlainMessage.php index d1e4e742..5151e4c0 100644 --- a/src/Message/PlainMessage.php +++ b/src/Message/PlainMessage.php @@ -3,13 +3,14 @@ namespace Bernard\Message; use ArrayAccess; +use Bernard\Message; /** * Simple message that gets you started. It has a name an a array of arguments * It does not enforce any types or properties so be careful on relying them * being there. */ -class PlainMessage extends AbstractMessage implements ArrayAccess +class PlainMessage implements Message, ArrayAccess { protected $name; protected $arguments; diff --git a/tests/Fixtures/SendNewsletterMessage.php b/tests/Fixtures/SendNewsletterMessage.php index 25c9765c..0fe779aa 100644 --- a/tests/Fixtures/SendNewsletterMessage.php +++ b/tests/Fixtures/SendNewsletterMessage.php @@ -2,7 +2,7 @@ namespace Bernard\Tests\Fixtures; -use Bernard\Message\AbstractMessage; +use Bernard\Message; use JMS\Serializer\Annotation as JMSSerializer; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; @@ -12,8 +12,10 @@ /** * This is a Custom implementation of a Message. */ -class SendNewsletterMessage extends AbstractMessage implements NormalizableInterface, DenormalizableInterface +class SendNewsletterMessage implements Message, NormalizableInterface, DenormalizableInterface { + use Message\HasName, Message\HasQueue; + /** * @JMSSerializer\Type("integer") * @JMSSerializer\SerializedName("newsletterId") diff --git a/tests/Message/AbstractMessageTest.php b/tests/Message/AbstractMessageTest.php deleted file mode 100644 index a2dd17fe..00000000 --- a/tests/Message/AbstractMessageTest.php +++ /dev/null @@ -1,21 +0,0 @@ -assertInstanceOf('Bernard\Message', new Fixtures\SendNewsletterMessage()); - $this->assertInstanceOf('Bernard\Message\AbstractMessage', new Fixtures\SendNewsletterMessage()); - } - - public function testItUsesClassNameAsNameAndQueueNameNormalized() - { - $message = new Fixtures\SendNewsletterMessage(); - $this->assertEquals('SendNewsletter', $message->getName()); - $this->assertEquals('send-newsletter', $message->getQueue()); - } -} From d8d543daba4780d46e7193a386aee630f234464e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 09:06:57 +0100 Subject: [PATCH 022/108] Improve the plain message - Made final - Added spec - Generic code improvements - Normalizer made final - Improved tests --- spec/Message/PlainMessageSpec.php | 46 ++++++++++++ src/Message/PlainMessage.php | 52 ++++++++----- src/Normalizer/PlainMessageNormalizer.php | 4 +- tests/Message/PlainMessageTest.php | 73 +++++++++++++++---- .../Normalizer/PlainMessageNormalizerTest.php | 27 +++++-- 5 files changed, 161 insertions(+), 41 deletions(-) create mode 100644 spec/Message/PlainMessageSpec.php diff --git a/spec/Message/PlainMessageSpec.php b/spec/Message/PlainMessageSpec.php new file mode 100644 index 00000000..0e189bef --- /dev/null +++ b/spec/Message/PlainMessageSpec.php @@ -0,0 +1,46 @@ +beConstructedWith('SendNewsletter'); + } + + function it_is_initializable() + { + $this->shouldHaveType(PlainMessage::class); + } + + function it_is_a_message() + { + $this->shouldImplement(Message::class); + } + + function it_has_a_name() + { + $this->getName()->shouldReturn('SendNewsletter'); + } + + function it_has_arguments() + { + $this->beConstructedWith( + 'SendNewsletter', + $args = [ + 'key1' => 1, + 'key2' => [1, 2, 3, 4], + 'key3' => null, + ] + ); + + $this->get('key1')->shouldReturn(1); + $this->has('key1')->shouldReturn(true); + $this->all()->shouldReturn($args); + } +} diff --git a/src/Message/PlainMessage.php b/src/Message/PlainMessage.php index 5151e4c0..63739ad2 100644 --- a/src/Message/PlainMessage.php +++ b/src/Message/PlainMessage.php @@ -2,18 +2,18 @@ namespace Bernard\Message; -use ArrayAccess; use Bernard\Message; /** - * Simple message that gets you started. It has a name an a array of arguments + * Simple message that gets you started. + * It has a name and an array of arguments. * It does not enforce any types or properties so be careful on relying them * being there. */ -class PlainMessage implements Message, ArrayAccess +final class PlainMessage implements Message, \ArrayAccess { - protected $name; - protected $arguments; + private $name; + private $arguments; /** * @param string $name @@ -25,6 +25,14 @@ public function __construct($name, array $arguments = []) $this->arguments = $arguments; } + /** + * {@inheritdoc} + */ + public function getName() + { + return $this->name; + } + /** * @return array */ @@ -34,33 +42,37 @@ public function all() } /** + * Returns the argument if found or null. + * * @param string $name * * @return mixed */ public function get($name) { - return $this->offsetGet($name); + return $this->has($name) ? $this->arguments[$name] : null; } /** + * Checks whether the arguments contain the given key. + * * @param string $name * * @return bool */ public function has($name) { - return $this->offsetExists($name); + return array_key_exists($name, $this->arguments); } - public function offsetExists($offset) + public function offsetGet($offset) { - return array_key_exists($offset, $this->arguments); + return $this->get($offset); } - public function offsetGet($offset) + public function offsetExists($offset) { - return $this->offsetExists($offset) ? $this->arguments[$offset] : null; + return $this->has($offset); } public function offsetSet($offset, $value) @@ -73,21 +85,23 @@ public function offsetUnset($offset) throw new \LogicException('Message is immutable'); } - /** - * {@inheritdoc} - */ - public function getName() + public function __get($property) { - return $this->name; + return $this->get($property); } - public function __get($property) + public function __isset($property) { - return $this->offsetGet($property); + return $this->has($property); } public function __set($property, $value) { - $this->offsetSet($property, $value); + throw new \LogicException('Message is immutable'); + } + + public function __unset($property) + { + throw new \LogicException('Message is immutable'); } } diff --git a/src/Normalizer/PlainMessageNormalizer.php b/src/Normalizer/PlainMessageNormalizer.php index e74205ae..9b635f00 100644 --- a/src/Normalizer/PlainMessageNormalizer.php +++ b/src/Normalizer/PlainMessageNormalizer.php @@ -7,7 +7,7 @@ use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; -class PlainMessageNormalizer implements NormalizerInterface, DenormalizerInterface +final class PlainMessageNormalizer implements NormalizerInterface, DenormalizerInterface { /** * {@inheritdoc} @@ -37,7 +37,7 @@ public function denormalize($data, $class, $format = null, array $context = []) */ public function supportsDenormalization($data, $type, $format = null) { - return $type === 'Bernard\Message\PlainMessage'; + return $type === PlainMessage::class; } /** diff --git a/tests/Message/PlainMessageTest.php b/tests/Message/PlainMessageTest.php index 71151588..fa6e164f 100644 --- a/tests/Message/PlainMessageTest.php +++ b/tests/Message/PlainMessageTest.php @@ -4,38 +4,81 @@ use Bernard\Message\PlainMessage; -class PlainMessageTest extends \PHPUnit\Framework\TestCase +final class PlainMessageTest extends \PHPUnit\Framework\TestCase { - public function testItHaveAName() + /** + * @test + */ + public function it_has_arguments() { - $message = $this->createMessage('SendNewsletter'); - - $this->assertEquals('SendNewsletter', $message->getName()); - } - - public function testItHasArguments() - { - $message = $this->createMessage('SendNewsletter', [ + $message = new PlainMessage('SendNewsletter', [ 'key1' => 1, 'key2' => [1, 2, 3, 4], 'key3' => null, ]); - $this->assertTrue(isset($message['key1'])); $this->assertTrue(isset($message['key1'])); $this->assertEquals(1, $message['key1']); $this->assertEquals([1, 2, 3, 4], $message['key2']); $this->assertInternalType('null', $message['key3']); + + $this->assertTrue(isset($message->key1)); + + $this->assertEquals(1, $message->key1); + $this->assertEquals([1, 2, 3, 4], $message->key2); + $this->assertNull($message->key3); + } + + /** + * @test + */ + public function it_implements_ArrayAccess() + { + $this->assertInstanceOf(\ArrayAccess::class, new PlainMessage('SendNewsletter')); } - public function testItImplementsArrayAccess() + /** + * @test + */ + public function it_is_immutable_to_magic_set() { - $this->assertInstanceOf('ArrayAccess', $this->createMessage('SendNewsletter')); + $this->expectException(\LogicException::class); + + $message = new PlainMessage('SendNewsletter'); + $message->key1 = 1; + } + + /** + * @test + */ + public function it_is_immutable_to_magic_unset() + { + $this->expectException(\LogicException::class); + + $message = new PlainMessage('SendNewsletter', ['key1' => 1]); + unset($message->key1); } - protected function createMessage($name, array $data = []) + /** + * @test + */ + public function it_is_immutable_to_offset_set() { - return new PlainMessage($name, $data); + $this->expectException(\LogicException::class); + + $message = new PlainMessage('SendNewsletter'); + $message['key1'] = 1; + } + + /** + * @test + */ + public function it_is_immutable_to_offset_unset() + { + $this->expectException(\LogicException::class); + + $message = new PlainMessage('SendNewsletter', ['key1' => 1]); + unset($message['key1']); } } diff --git a/tests/Normalizer/PlainMessageNormalizerTest.php b/tests/Normalizer/PlainMessageNormalizerTest.php index 30993af0..6f0d11b0 100644 --- a/tests/Normalizer/PlainMessageNormalizerTest.php +++ b/tests/Normalizer/PlainMessageNormalizerTest.php @@ -5,12 +5,29 @@ use Bernard\Message\PlainMessage; use Bernard\Normalizer\PlainMessageNormalizer; -class PlainMessageNormalizerTest extends \PHPUnit\Framework\TestCase +final class PlainMessageNormalizerTest extends \PHPUnit\Framework\TestCase { - public function testDenormalize() + /** + * @test + */ + public function it_normalizes_a_message() { - $sut = new PlainMessageNormalizer(); - $normalized = $sut->denormalize(['name' => 'foobar', 'arguments' => []], null); - $this->assertTrue($normalized instanceof PlainMessage); + $normalizer = new PlainMessageNormalizer(); + + $normalized = $normalizer->normalize(new PlainMessage('foobar')); + + $this->assertEquals(['name' => 'foobar', 'arguments' => []], $normalized); + } + + /** + * @test + */ + public function it_denormalizes_a_normalized_message() + { + $normalizer = new PlainMessageNormalizer(); + + $denormalized = $normalizer->denormalize(['name' => 'foobar', 'arguments' => []], null); + + $this->assertInstanceOf(PlainMessage::class, $denormalized); } } From 7b5aa6fb2c680ebb2f49d1e5c522e9b3571a1ba3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 09:32:39 +0100 Subject: [PATCH 023/108] Make envelope final --- src/Envelope.php | 8 ++++---- tests/EnvelopeTest.php | 9 ++++++--- tests/Event/EnvelopeEventTest.php | 5 ++++- tests/Event/RejectEnvelopeEventTest.php | 7 +++++-- tests/EventListener/ErrorLogSubscriberTest.php | 14 +++++++++----- 5 files changed, 28 insertions(+), 15 deletions(-) diff --git a/src/Envelope.php b/src/Envelope.php index b5d6d437..1630e1a1 100644 --- a/src/Envelope.php +++ b/src/Envelope.php @@ -6,11 +6,11 @@ * Wraps a Message with metadata that can be used for automatic retry * or inspection. */ -class Envelope +final class Envelope { - protected $message; - protected $class; - protected $timestamp; + private $message; + private $class; + private $timestamp; /** * @param Message $message diff --git a/tests/EnvelopeTest.php b/tests/EnvelopeTest.php index cee73572..b662b3b3 100644 --- a/tests/EnvelopeTest.php +++ b/tests/EnvelopeTest.php @@ -5,14 +5,17 @@ use Bernard\Message\PlainMessage; use Bernard\Envelope; -class EnvelopeTest extends \PHPUnit\Framework\TestCase +final class EnvelopeTest extends \PHPUnit\Framework\TestCase { - public function testItWrapsAMessageWithMetadata() + /** + * @test + */ + public function it_wraps_a_message_with_metadata() { $envelope = new Envelope($message = new PlainMessage('SendNewsletter')); $this->assertEquals(time(), $envelope->getTimestamp()); - $this->assertEquals('Bernard\Message\PlainMessage', $envelope->getClass()); + $this->assertEquals(PlainMessage::class, $envelope->getClass()); $this->assertEquals('SendNewsletter', $envelope->getName()); $this->assertSame($message, $envelope->getMessage()); } diff --git a/tests/Event/EnvelopeEventTest.php b/tests/Event/EnvelopeEventTest.php index 898a69c6..388b9d4b 100644 --- a/tests/Event/EnvelopeEventTest.php +++ b/tests/Event/EnvelopeEventTest.php @@ -2,14 +2,17 @@ namespace Bernard\Tests\Event; +use Bernard\Envelope; use Bernard\Event\EnvelopeEvent; +use Bernard\Message; class EnvelopeEventTest extends \PHPUnit\Framework\TestCase { public function setUp() { - $this->envelope = $this->getMockBuilder('Bernard\Envelope')->disableOriginalConstructor() + $message = $this->getMockBuilder(Message::class)->disableOriginalConstructor() ->getMock(); + $this->envelope = new Envelope($message); $this->queue = $this->createMock('Bernard\Queue'); } diff --git a/tests/Event/RejectEnvelopeEventTest.php b/tests/Event/RejectEnvelopeEventTest.php index 52241b08..4663610b 100644 --- a/tests/Event/RejectEnvelopeEventTest.php +++ b/tests/Event/RejectEnvelopeEventTest.php @@ -2,7 +2,9 @@ namespace Bernard\Tests\Event; +use Bernard\Envelope; use Bernard\Event\RejectEnvelopeEvent; +use Bernard\Message; class RejectEnvelopeEventTest extends \PHPUnit\Framework\TestCase { @@ -18,8 +20,9 @@ class RejectEnvelopeEventTest extends \PHPUnit\Framework\TestCase public function setUp() { - $this->envelope = $this->getMockBuilder('Bernard\Envelope') - ->disableOriginalConstructor()->getMock(); + $message = $this->getMockBuilder(Message::class)->disableOriginalConstructor() + ->getMock(); + $this->envelope = new Envelope($message); $this->queue = $this->createMock('Bernard\Queue'); } diff --git a/tests/EventListener/ErrorLogSubscriberTest.php b/tests/EventListener/ErrorLogSubscriberTest.php index 8b6b2eab..e3f81341 100644 --- a/tests/EventListener/ErrorLogSubscriberTest.php +++ b/tests/EventListener/ErrorLogSubscriberTest.php @@ -2,11 +2,14 @@ namespace Bernard\Tests\EventListener; +use Bernard\Envelope; use Bernard\Event\RejectEnvelopeEvent; use Bernard\EventListener\ErrorLogSubscriber; +use Bernard\Message; class ErrorLogSubscriberTest extends \PHPUnit\Framework\TestCase { + private $message; private $envelope; private $queue; private $producer; @@ -20,8 +23,9 @@ public function setUp() $this->markTestSkipped("HHVM does not support `ini_set('error_log', '/path/to/log')`"); } - $this->envelope = $this->getMockBuilder('Bernard\Envelope') - ->disableOriginalConstructor()->getMock(); + $this->message = $this->getMockBuilder(Message::class)->disableOriginalConstructor() + ->getMock(); + $this->envelope = new Envelope($this->message); $this->queue = $this->createMock('Bernard\Queue'); $this->producer = $this->getMockBuilder('Bernard\Producer')->disableOriginalConstructor()->getMock(); $this->subscriber = new ErrorLogSubscriber($this->producer, 'failures'); @@ -48,7 +52,7 @@ public function testGetSubscribedEvents() public function testOnRejectException() { - $this->envelope->expects($this->once()) + $this->message->expects($this->once()) ->method('getName') ->willReturn('foo'); $error = new \Exception('bar'); @@ -64,7 +68,7 @@ public function testOnRejectException() */ public function testOnRejectError() { - $this->envelope->expects($this->once()) + $this->message->expects($this->once()) ->method('getName') ->willReturn('foo'); $error = new \TypeError('bar'); @@ -77,7 +81,7 @@ public function testOnRejectError() public function testOnRejectObject() { - $this->envelope->expects($this->once()) + $this->message->expects($this->once()) ->method('getName') ->willReturn('foo'); $error = new \stdClass(); From c12ec8fdba839dbbca54472fd70ee86658dc0967 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 09:41:40 +0100 Subject: [PATCH 024/108] Improve EnvelopeNormalizer --- .../AbstractAggregateNormalizerAware.php | 19 ---------- src/Normalizer/EnvelopeNormalizer.php | 35 +++++++++++++++---- 2 files changed, 29 insertions(+), 25 deletions(-) delete mode 100644 src/Normalizer/AbstractAggregateNormalizerAware.php diff --git a/src/Normalizer/AbstractAggregateNormalizerAware.php b/src/Normalizer/AbstractAggregateNormalizerAware.php deleted file mode 100644 index 611a5721..00000000 --- a/src/Normalizer/AbstractAggregateNormalizerAware.php +++ /dev/null @@ -1,19 +0,0 @@ -aggregate = $aggregate; - } -} diff --git a/src/Normalizer/EnvelopeNormalizer.php b/src/Normalizer/EnvelopeNormalizer.php index cbc3db2e..294dd93e 100644 --- a/src/Normalizer/EnvelopeNormalizer.php +++ b/src/Normalizer/EnvelopeNormalizer.php @@ -3,12 +3,27 @@ namespace Bernard\Normalizer; use Assert\Assertion; +use Assert\AssertionFailedException; use Bernard\Envelope; +use Normalt\Normalizer\AggregateNormalizer; +use Normalt\Normalizer\AggregateNormalizerAware; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; +use Symfony\Component\Serializer\Exception\RuntimeException; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; -class EnvelopeNormalizer extends AbstractAggregateNormalizerAware implements NormalizerInterface, DenormalizerInterface +final class EnvelopeNormalizer implements NormalizerInterface, DenormalizerInterface, AggregateNormalizerAware { + private $aggregate; + + /** + * @param AggregateNormalizer $aggregate + */ + public function setAggregateNormalizer(AggregateNormalizer $aggregate) + { + $this->aggregate = $aggregate; + } + /** * {@inheritdoc} */ @@ -26,9 +41,12 @@ public function normalize($object, $format = null, array $context = []) */ public function denormalize($data, $class, $format = null, array $context = []) { - Assertion::choicesNotEmpty($data, ['message', 'class', 'timestamp']); - - Assertion::classExists($data['class']); + try { + Assertion::choicesNotEmpty($data, ['message', 'class', 'timestamp']); + Assertion::classExists($data['class']); + } catch (AssertionFailedException $e) { + throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); + } $envelope = new Envelope($this->aggregate->denormalize($data['message'], $data['class'])); @@ -43,7 +61,7 @@ public function denormalize($data, $class, $format = null, array $context = []) */ public function supportsDenormalization($data, $type, $format = null) { - return $type === 'Bernard\Envelope'; + return $type === Envelope::class; } /** @@ -61,7 +79,12 @@ public function supportsNormalization($data, $format = null) */ private function forcePropertyValue(Envelope $envelope, $property, $value) { - $property = new \ReflectionProperty($envelope, $property); + try { + $property = new \ReflectionProperty($envelope, $property); + } catch (\ReflectionException $e) { + throw new RuntimeException($e->getMessage(), $e->getCode(), $e); + } + $property->setAccessible(true); $property->setValue($envelope, $value); } From 62e7c8bbfa1a6cd9186b4419fbdffcafa8ecdbab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 09:42:37 +0100 Subject: [PATCH 025/108] Handle exceptions properly in PlainMessageNormalizer --- src/Normalizer/PlainMessageNormalizer.php | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/Normalizer/PlainMessageNormalizer.php b/src/Normalizer/PlainMessageNormalizer.php index 9b635f00..a77953fb 100644 --- a/src/Normalizer/PlainMessageNormalizer.php +++ b/src/Normalizer/PlainMessageNormalizer.php @@ -3,7 +3,9 @@ namespace Bernard\Normalizer; use Assert\Assertion; +use Assert\AssertionFailedException; use Bernard\Message\PlainMessage; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; @@ -25,9 +27,13 @@ public function normalize($object, $format = null, array $context = []) */ public function denormalize($data, $class, $format = null, array $context = []) { - Assertion::notEmptyKey($data, 'name'); - Assertion::keyExists($data, 'arguments'); - Assertion::isArray($data['arguments']); + try { + Assertion::notEmptyKey($data, 'name'); + Assertion::keyExists($data, 'arguments'); + Assertion::isArray($data['arguments']); + } catch (AssertionFailedException $e) { + throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); + } return new PlainMessage($data['name'], $data['arguments']); } From 7022edce9ea9ed7a59b5d0f843502530a184760c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Thu, 15 Feb 2018 10:01:44 +0100 Subject: [PATCH 026/108] Fix specs --- spec/Normalizer/EnvelopeNormalizerSpec.php | 10 +++++----- spec/Router/ClassNameRouterSpec.php | 10 +++++----- spec/SerializerSpec.php | 8 ++++++-- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/spec/Normalizer/EnvelopeNormalizerSpec.php b/spec/Normalizer/EnvelopeNormalizerSpec.php index b0cbc273..7ad31fe1 100644 --- a/spec/Normalizer/EnvelopeNormalizerSpec.php +++ b/spec/Normalizer/EnvelopeNormalizerSpec.php @@ -17,11 +17,11 @@ function it_is_a_normalizer_and_denormailzer() $this->shouldImplement(DenormalizerInterface::class); } - function it_normalizes_envelope_and_delegates_message_to_aggregate(Envelope $envelope, Message $message, AggregateNormalizer $aggregate) + function it_normalizes_envelope_and_delegates_message_to_aggregate(AggregateNormalizer $aggregate) { - $envelope->getMessage()->willReturn($message); - $envelope->getClass()->willReturn(Message\PlainMessage::class); - $envelope->getTimestamp()->willReturn(1337); + $message = new Message\PlainMessage('message'); + $envelope = new Envelope($message); + $time = time(); $aggregate->normalize($message)->willReturn([ 'key' => 'value', @@ -31,7 +31,7 @@ function it_normalizes_envelope_and_delegates_message_to_aggregate(Envelope $env $this->normalize($envelope)->shouldReturn([ 'class' => Message\PlainMessage::class, - 'timestamp' => 1337, + 'timestamp' => $time, 'message' => ['key' => 'value'], ]); } diff --git a/spec/Router/ClassNameRouterSpec.php b/spec/Router/ClassNameRouterSpec.php index f4961936..2a936ecb 100644 --- a/spec/Router/ClassNameRouterSpec.php +++ b/spec/Router/ClassNameRouterSpec.php @@ -14,7 +14,7 @@ class ClassNameRouterSpec extends ObjectBehavior function let() { $this->beConstructedWith([ - Message::class => function() {}, + Message\PlainMessage::class => function() {}, ]); } @@ -28,16 +28,16 @@ function it_is_a_router() $this->shouldImplement(Router::class); } - function it_maps_an_envelope(Envelope $envelope) + function it_maps_an_envelope() { - $envelope->getClass()->willReturn(Message\PlainMessage::class); + $envelope = new Envelope(new Message\PlainMessage('SendNewsletter')); $this->map($envelope)->shouldBeCallable(); } - function it_throws_an_exception_when_envelope_cannot_be_mapped(Envelope $envelope) + function it_throws_an_exception_when_envelope_cannot_be_mapped(Message $message) { - $envelope->getClass()->willReturn(\stdClass::class); + $envelope = new Envelope($message->getWrappedObject()); $this->shouldThrow(ReceiverNotFoundException::class)->duringMap($envelope); } diff --git a/spec/SerializerSpec.php b/spec/SerializerSpec.php index b56d6878..567878b6 100644 --- a/spec/SerializerSpec.php +++ b/spec/SerializerSpec.php @@ -3,6 +3,7 @@ namespace spec\Bernard; use Bernard\Envelope; +use Bernard\Message; use Bernard\Message\PlainMessage; use Normalt\Normalizer\AggregateNormalizer; @@ -13,8 +14,9 @@ function let(AggregateNormalizer $aggregate) $this->beConstructedWith($aggregate); } - function it_serializes_normalized_envelope_into_json(Envelope $envelope, AggregateNormalizer $aggregate) + function it_serializes_normalized_envelope_into_json(Message $message, AggregateNormalizer $aggregate) { + $envelope = new Envelope($message->getWrappedObject()); $aggregate->normalize($envelope, null)->willReturn([ 'class' => PlainMessage::class, 'timestamp' => 1337, @@ -25,8 +27,10 @@ function it_serializes_normalized_envelope_into_json(Envelope $envelope, Aggrega ->shouldReturn('{"class":"Bernard\\\\Message\\\\PlainMessage","timestamp":1337,"message":{"name":"Import","arguments":{"arg1":"value"}}}'); } - function it_unserializes_into_envelope(Envelope $envelope, AggregateNormalizer $aggregate) + function it_unserializes_into_envelope(Message $message, AggregateNormalizer $aggregate) { + $envelope = new Envelope($message->getWrappedObject()); + $normalized = [ 'class' => PlainMessage::class, 'timestamp' => 1337, From cf9423322690533f45a300de6852658145ed3eae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Fri, 16 Feb 2018 01:10:37 +0100 Subject: [PATCH 027/108] Improve specs --- spec/Normalizer/EnvelopeNormalizerSpec.php | 21 ++++++++++----- .../Normalizer/PlainMessageNormalizerSpec.php | 26 +++++++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 spec/Normalizer/PlainMessageNormalizerSpec.php diff --git a/spec/Normalizer/EnvelopeNormalizerSpec.php b/spec/Normalizer/EnvelopeNormalizerSpec.php index 7ad31fe1..f3537e47 100644 --- a/spec/Normalizer/EnvelopeNormalizerSpec.php +++ b/spec/Normalizer/EnvelopeNormalizerSpec.php @@ -4,6 +4,7 @@ use Bernard\Envelope; use Bernard\Message; +use Bernard\Normalizer\EnvelopeNormalizer; use Normalt\Normalizer\AggregateNormalizer; use PhpSpec\ObjectBehavior; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; @@ -11,16 +12,24 @@ class EnvelopeNormalizerSpec extends ObjectBehavior { - function it_is_a_normalizer_and_denormailzer() + function it_is_initializable() + { + $this->shouldHaveType(EnvelopeNormalizer::class); + } + + function it_is_a_normalizer() { $this->shouldImplement(NormalizerInterface::class); + } + + function it_is_adenormailzer() + { $this->shouldImplement(DenormalizerInterface::class); } - function it_normalizes_envelope_and_delegates_message_to_aggregate(AggregateNormalizer $aggregate) + function it_normalizes_envelope_and_delegates_message_to_aggregate(Message $message, AggregateNormalizer $aggregate) { - $message = new Message\PlainMessage('message'); - $envelope = new Envelope($message); + $envelope = new Envelope($message->getWrappedObject()); $time = time(); $aggregate->normalize($message)->willReturn([ @@ -30,7 +39,7 @@ function it_normalizes_envelope_and_delegates_message_to_aggregate(AggregateNorm $this->setAggregateNormalizer($aggregate); $this->normalize($envelope)->shouldReturn([ - 'class' => Message\PlainMessage::class, + 'class' => get_class($message->getWrappedObject()), 'timestamp' => $time, 'message' => ['key' => 'value'], ]); @@ -48,7 +57,7 @@ function it_denormalizes_envelope_and_delegates_message_to_aggregate(Message $me 'message' => ['key' => 'value'], ]; - $envelope = $this->denormalize($normalized, Envelope::class); + $envelope = $this->denormalize($normalized, null); $envelope->shouldHaveType(Envelope::class); $envelope->getMessage()->shouldReturn($message); $envelope->getTimestamp()->shouldReturn(1337); diff --git a/spec/Normalizer/PlainMessageNormalizerSpec.php b/spec/Normalizer/PlainMessageNormalizerSpec.php new file mode 100644 index 00000000..1f36a036 --- /dev/null +++ b/spec/Normalizer/PlainMessageNormalizerSpec.php @@ -0,0 +1,26 @@ +shouldHaveType(PlainMessageNormalizer::class); + } + + function it_is_a_normalizer() + { + $this->shouldImplement(NormalizerInterface::class); + } + + function it_is_adenormailzer() + { + $this->shouldImplement(DenormalizerInterface::class); + } +} From c0b810201437d138e34ed0bce620328f3145379d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Fri, 16 Feb 2018 02:25:07 +0100 Subject: [PATCH 028/108] Add PSR-11 container router --- composer.json | 3 +- doc/consuming.rst | 9 ++++- spec/Router/ContainerRouterSpec.php | 63 +++++++++++++++++++++++++++++ src/Router/ContainerRouter.php | 48 ++++++++++++++++++++++ 4 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 spec/Router/ContainerRouterSpec.php create mode 100644 src/Router/ContainerRouter.php diff --git a/composer.json b/composer.json index 0c27ea26..25a3b554 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,8 @@ "beberlei/assert": "~2.1" }, "require-dev" : { - "psr/log": "~1.0", + "psr/log": "^1.0", + "psr/container": "^1.0", "pimple/pimple": "~1.0", "predis/predis": "~0.8", "symfony/console": "^2.7|^3.0|^4.0", diff --git a/doc/consuming.rst b/doc/consuming.rst index b93e39be..cd0789a4 100644 --- a/doc/consuming.rst +++ b/doc/consuming.rst @@ -24,9 +24,14 @@ object should handle which messages, you are required to register them first. $router = new SimpleRouter(); $router->add('SendNewsletter', new NewsletterMessageHandler); - // Bernard also comes with a router for Pimple (Silex) which allows you + // Bernard also comes with a router for PSR-11 container which allows you // to use service ids and have your service object lazy loader. // + // $router = new \Bernard\Router\ContainerRouter($container); + // $router->add('SendNewsletter', 'my.service.id'); + // + // Pimple (Silex) is also supported. + // // $router = new \Bernard\Router\PimpleAwareRouter($pimple); // $router->add('SendNewsletter', 'my.service.id'); // @@ -37,7 +42,7 @@ object should handle which messages, you are required to register them first. // Create a Consumer and start the loop. $consumer = new Consumer($router, $eventDispatcher); - + // The second argument is optional and is an array // of options. Currently only ``max-runtime`` is supported which specifies the max runtime // in seconds. diff --git a/spec/Router/ContainerRouterSpec.php b/spec/Router/ContainerRouterSpec.php new file mode 100644 index 00000000..48ef9ad9 --- /dev/null +++ b/spec/Router/ContainerRouterSpec.php @@ -0,0 +1,63 @@ +beConstructedWith($container); + } + + function it_is_initializable() + { + $this->shouldHaveType(ContainerRouter::class); + } + + function it_is_a_router() + { + $this->shouldImplement(Router::class); + } + + function it_maps_an_envelope(Message $message, ContainerInterface $container) + { + $this->beConstructedWith( + $container, + [ + 'message' => 'my.service', + ] + ); + + $message->getName()->willReturn('message'); + + $container->has('my.service')->willReturn(true); + $container->get('my.service')->willReturn(function () {}); + + $envelope = new Envelope($message->getWrappedObject()); + + $this->map($envelope)->shouldBeCallable(); + } + + function it_throws_an_exception_when_envelope_cannot_be_mapped(Message $message, ContainerInterface $container) + { + $message->getName()->willReturn('message'); + + $container->has('my.service')->willReturn(true); + $container->get('my.service')->willThrow(NotFoundException::class); + + $envelope = new Envelope($message->getWrappedObject()); + + $this->shouldThrow(ReceiverNotFoundException::class)->duringMap($envelope); + } +} diff --git a/src/Router/ContainerRouter.php b/src/Router/ContainerRouter.php new file mode 100644 index 00000000..c43e30ea --- /dev/null +++ b/src/Router/ContainerRouter.php @@ -0,0 +1,48 @@ +container = $container; + + parent::__construct($receivers); + } + + /** + * {@inheritdoc} + */ + protected function get($name) + { + $serviceId = parent::get($name); + $serviceId = $serviceId ?: ''; + + try { + return $this->container->get($serviceId); + } catch (NotFoundExceptionInterface $e) { + return null; + } + } + + /** + * {@inheritdoc} + */ + protected function accepts($receiver) + { + return $this->container->has($receiver); + } +} From d7d858b41bb7c3200574864e4128ae8da7318cf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Fri, 16 Feb 2018 02:53:21 +0100 Subject: [PATCH 029/108] Remove Symfony container router As of Symfony 3.3 the DependencyInjection component implements PSR-11. Use the provided ContainerRouter instead. Related #365 --- composer.json | 1 - doc/consuming.rst | 5 --- src/Router/ContainerAwareRouter.php | 40 ------------------ tests/Router/ContainerAwareRouterTest.php | 49 ----------------------- 4 files changed, 95 deletions(-) delete mode 100644 src/Router/ContainerAwareRouter.php delete mode 100644 tests/Router/ContainerAwareRouterTest.php diff --git a/composer.json b/composer.json index 25a3b554..396c148c 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,6 @@ "pimple/pimple": "~1.0", "predis/predis": "~0.8", "symfony/console": "^2.7|^3.0|^4.0", - "symfony/dependency-injection": "^2.7|^3.0|^4.0", "doctrine/dbal": "~2.3", "aws/aws-sdk-php": "~2.4|~3.0", "pda/pheanstalk": "~3.0", diff --git a/doc/consuming.rst b/doc/consuming.rst index cd0789a4..99181354 100644 --- a/doc/consuming.rst +++ b/doc/consuming.rst @@ -34,11 +34,6 @@ object should handle which messages, you are required to register them first. // // $router = new \Bernard\Router\PimpleAwareRouter($pimple); // $router->add('SendNewsletter', 'my.service.id'); - // - // Symfony DependencyInjection component is also supported. - // - // $router = new \Bernard\Router\ContainerAwareRouter($container); - // $router->add('SendNewsletter', 'my.service.id'); // Create a Consumer and start the loop. $consumer = new Consumer($router, $eventDispatcher); diff --git a/src/Router/ContainerAwareRouter.php b/src/Router/ContainerAwareRouter.php deleted file mode 100644 index e3e3e0a1..00000000 --- a/src/Router/ContainerAwareRouter.php +++ /dev/null @@ -1,40 +0,0 @@ -container = $container; - - parent::__construct($receivers); - } - - /** - * {@inheritdoc} - */ - protected function get($name) - { - $serviceId = parent::get($name); - $serviceId = null !== $serviceId ? $serviceId : ''; - - return $this->container->get($serviceId); - } - - /** - * {@inheritdoc} - */ - protected function accepts($receiver) - { - return $this->container->has($receiver); - } -} diff --git a/tests/Router/ContainerAwareRouterTest.php b/tests/Router/ContainerAwareRouterTest.php deleted file mode 100644 index 8da8bb7d..00000000 --- a/tests/Router/ContainerAwareRouterTest.php +++ /dev/null @@ -1,49 +0,0 @@ -container = new Container(); - $this->container->set('my.service', function () { - return 'var_dump'; - }); - } - - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - */ - public function testUndefinedServicesAreNotAccepted() - { - $envelope = new Envelope(new PlainMessage('SendNewsletter')); - - $router = new ContainerAwareRouter($this->container); - $router->map($envelope); - } - - public function testAcceptsInConstructor() - { - $router = new ContainerAwareRouter($this->container, ['SendNewsletter' => 'my.service']); - $envelope = new Envelope(new PlainMessage('SendNewsletter')); - - $this->assertSame($this->container->get('my.service'), $router->map($envelope)); - } - - public function testAcceptsContainerServiceAsReceiver() - { - $envelope = new Envelope(new PlainMessage('SendNewsletter')); - - $router = new ContainerAwareRouter($this->container, [ - 'SendNewsletter' => 'my.service', - ]); - - $this->assertSame($this->container->get('my.service'), $router->map($envelope)); - } -} From b5191f7eb0cf999d3bd2138e67697cdd7a91f58a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Fri, 16 Feb 2018 02:55:04 +0100 Subject: [PATCH 030/108] Remove League container router League container implements container-interop which extends PSR-11. Use the provided ContainerRouter instead. Related #365 --- composer.json | 1 - src/Router/LeagueContainerAwareRouter.php | 39 ------------------- .../Router/LeagueContainerAwareRouterTest.php | 38 ------------------ 3 files changed, 78 deletions(-) delete mode 100644 src/Router/LeagueContainerAwareRouter.php delete mode 100644 tests/Router/LeagueContainerAwareRouterTest.php diff --git a/composer.json b/composer.json index 396c148c..df96637d 100644 --- a/composer.json +++ b/composer.json @@ -26,7 +26,6 @@ "leanphp/phpspec-code-coverage": "^3.0 || ^4.0", "phpunit/phpunit": "^5.5 || ^6.0 || ^7.0", "iron-io/iron_mq": "~4.0", - "league/container": "~2.3", "queue-interop/queue-interop": "^0.6", "queue-interop/amqp-interop": "^0.6" }, diff --git a/src/Router/LeagueContainerAwareRouter.php b/src/Router/LeagueContainerAwareRouter.php deleted file mode 100644 index 3ebd4a50..00000000 --- a/src/Router/LeagueContainerAwareRouter.php +++ /dev/null @@ -1,39 +0,0 @@ -container = $container; - - parent::__construct($receivers); - } - - /** - * {@inheritdoc} - */ - protected function get($name) - { - $serviceId = parent::get($name); - - return $this->container->get($serviceId); - } - - /** - * {@inheritdoc} - */ - protected function accepts($receiver) - { - return $this->container->has($receiver); - } -} diff --git a/tests/Router/LeagueContainerAwareRouterTest.php b/tests/Router/LeagueContainerAwareRouterTest.php deleted file mode 100644 index 23e446c8..00000000 --- a/tests/Router/LeagueContainerAwareRouterTest.php +++ /dev/null @@ -1,38 +0,0 @@ -container = new Container(); - $this->container->add('my.service', function () { - return 'var_dump'; - }); - } - - /** - * @expectedException \League\Container\Exception\NotFoundException - */ - public function testUndefinedServicesAreNotAccepted() - { - $envelope = new Envelope(new PlainMessage('SendNewsletter')); - - $router = new LeagueContainerAwareRouter($this->container); - $router->map($envelope); - } - - public function testAcceptsInConstructor() - { - $router = new LeagueContainerAwareRouter($this->container, ['SendNewsletter' => 'my.service']); - $envelope = new Envelope(new PlainMessage('SendNewsletter')); - - $this->assertSame($this->container->get('my.service'), $router->map($envelope)); - } -} From 601b61638f85688116c6e2b64ab09a47cf30c50f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Fri, 16 Feb 2018 02:56:36 +0100 Subject: [PATCH 031/108] Remove Pimple container router Pimple contains a PSR-11 wrapper. Use the provided ContainerRouter instead. Related #365 --- composer.json | 1 - doc/consuming.rst | 5 --- src/Router/PimpleAwareRouter.php | 37 -------------------- tests/Router/PimpleAwareRouterTest.php | 48 -------------------------- 4 files changed, 91 deletions(-) delete mode 100644 src/Router/PimpleAwareRouter.php delete mode 100644 tests/Router/PimpleAwareRouterTest.php diff --git a/composer.json b/composer.json index df96637d..9fdcaf7a 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,6 @@ "require-dev" : { "psr/log": "^1.0", "psr/container": "^1.0", - "pimple/pimple": "~1.0", "predis/predis": "~0.8", "symfony/console": "^2.7|^3.0|^4.0", "doctrine/dbal": "~2.3", diff --git a/doc/consuming.rst b/doc/consuming.rst index 99181354..877c8bcb 100644 --- a/doc/consuming.rst +++ b/doc/consuming.rst @@ -29,11 +29,6 @@ object should handle which messages, you are required to register them first. // // $router = new \Bernard\Router\ContainerRouter($container); // $router->add('SendNewsletter', 'my.service.id'); - // - // Pimple (Silex) is also supported. - // - // $router = new \Bernard\Router\PimpleAwareRouter($pimple); - // $router->add('SendNewsletter', 'my.service.id'); // Create a Consumer and start the loop. $consumer = new Consumer($router, $eventDispatcher); diff --git a/src/Router/PimpleAwareRouter.php b/src/Router/PimpleAwareRouter.php deleted file mode 100644 index a429fe09..00000000 --- a/src/Router/PimpleAwareRouter.php +++ /dev/null @@ -1,37 +0,0 @@ -pimple = $pimple; - - parent::__construct($receivers); - } - - /** - * {@inheritdoc} - */ - protected function get($name) - { - return $this->pimple[parent::get($name)]; - } - - /** - * {@inheritdoc} - */ - protected function accepts($receiver) - { - return isset($this->pimple[$receiver]); - } -} diff --git a/tests/Router/PimpleAwareRouterTest.php b/tests/Router/PimpleAwareRouterTest.php deleted file mode 100644 index b43757df..00000000 --- a/tests/Router/PimpleAwareRouterTest.php +++ /dev/null @@ -1,48 +0,0 @@ -pimple = new Pimple(); - $this->pimple['my.service'] = $this->pimple->share(function () { - return 'var_dump'; - }); - - $this->router = new PimpleAwareRouter($this->pimple); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testUndefinedServicesAreNotAccepted() - { - $envelope = new Envelope(new PlainMessage('SendNewsletter')); - - $this->router->map($envelope); - } - - public function testAcceptsInConstructor() - { - $router = new PimpleAwareRouter($this->pimple, ['SendNewsletter' => 'my.service']); - $envelope = new Envelope(new PlainMessage('SendNewsletter')); - - $this->assertSame($this->pimple['my.service'], $router->map($envelope)); - } - - public function testAcceptsPimpleServiceAsReceiver() - { - $envelope = new Envelope(new PlainMessage('SendNewsletter')); - - $this->router->add('SendNewsletter', 'my.service'); - - $this->assertSame($this->pimple['my.service'], $this->router->map($envelope)); - } -} From 3ab457ee62b3952a99138000275a2a99b04a6fad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Fri, 16 Feb 2018 03:16:22 +0100 Subject: [PATCH 032/108] Move Exception marker interface to the root package This is the pattern that we followed with other interfaces. Fixes #367 --- src/{Exception => }/Exception.php | 2 +- src/Exception/InvalidArgumentException.php | 2 ++ src/Exception/InvalidOperationException.php | 2 ++ src/Exception/NotImplementedException.php | 2 ++ src/Exception/QueueNotFoundException.php | 2 ++ src/Exception/ReceiverNotFoundException.php | 2 ++ src/Exception/ServiceUnavailableException.php | 2 ++ tests/Exception/ExceptionTest.php | 7 +++++-- 8 files changed, 18 insertions(+), 3 deletions(-) rename src/{Exception => }/Exception.php (75%) diff --git a/src/Exception/Exception.php b/src/Exception.php similarity index 75% rename from src/Exception/Exception.php rename to src/Exception.php index 27ad484f..5bcc42a7 100644 --- a/src/Exception/Exception.php +++ b/src/Exception.php @@ -1,6 +1,6 @@ assertInstanceOf('\Bernard\Exception\Exception', $e); + } catch (Exception $e) { + $this->assertInstanceOf(Exception::class, $e); $this->assertInstanceOf($exception, $e); $this->assertInstanceOf($base, $e); return; } + $this->fail('Exception not caught'); } From c554419d7971c70055ae4c541f307dd2ec1fff01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Fri, 16 Feb 2018 05:24:07 +0100 Subject: [PATCH 033/108] Fix circular dependency in the example Fixes #323 Since there are no subscribers registered for events dispatched by the producer, a dummy event dispatcher instance will do for now. --- example/bootstrap.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/bootstrap.php b/example/bootstrap.php index 10a89aea..c2177c4a 100644 --- a/example/bootstrap.php +++ b/example/bootstrap.php @@ -45,7 +45,7 @@ function get_queue_factory() function get_producer() { - return new Producer(get_queue_factory(), get_event_dispatcher()); + return new Producer(get_queue_factory(), new EventDispatcher()); } function get_receivers() From 16a5e2c0cab6151567fbcd8afdbba17323f75d36 Mon Sep 17 00:00:00 2001 From: elazar Date: Wed, 6 Dec 2017 13:52:16 -0600 Subject: [PATCH 034/108] Add missing case for SqsClient queue creation SqsDriver currently handles SQS returning a 400 response if a queue does not exist when attempting to create it. However, SQS may also return a 404, which SqsDriver does not currently handle. This commit adds a check for the 404 case so that the queue is also created in that case. Refs #294, #295, #327 --- src/Driver/Sqs/Driver.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Driver/Sqs/Driver.php b/src/Driver/Sqs/Driver.php index a09ff6de..aa7dacec 100644 --- a/src/Driver/Sqs/Driver.php +++ b/src/Driver/Sqs/Driver.php @@ -15,6 +15,7 @@ final class Driver extends AbstractPrefetchDriver { const AWS_SQS_FIFO_SUFFIX = '.fifo'; const AWS_SQS_EXCEPTION_BAD_REQUEST = 400; + const AWS_SQS_EXCEPTION_NOT_FOUND = 404; private $sqs; private $queueUrls; @@ -100,8 +101,10 @@ private function queueExists($queueName) return false; } catch (SqsException $exception) { if ($previousException = $exception->getPrevious()) { - if ($previousException->getCode() === self::AWS_SQS_EXCEPTION_BAD_REQUEST) { - return false; + switch ($previousException->getCode()) { + case self::AWS_SQS_EXCEPTION_BAD_REQUEST: + case self::AWS_SQS_EXCEPTION_NOT_FOUND: + return false; } } From 2dca202a8839b7690072b45fb905d1675840ec17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 08:07:50 +0100 Subject: [PATCH 035/108] Remove unused invalid argument exception --- src/Exception/InvalidArgumentException.php | 9 --------- tests/Exception/ExceptionTest.php | 1 - 2 files changed, 10 deletions(-) delete mode 100644 src/Exception/InvalidArgumentException.php diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php deleted file mode 100644 index ef01bbe7..00000000 --- a/src/Exception/InvalidArgumentException.php +++ /dev/null @@ -1,9 +0,0 @@ - Date: Sun, 18 Feb 2018 08:11:47 +0100 Subject: [PATCH 036/108] Improve invalid operation exception --- .../InvalidOperationExceptionSpec.php | 20 +++++++++++++++++++ src/Exception/InvalidOperationException.php | 6 +++++- tests/Exception/ExceptionTest.php | 1 - 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 spec/Exception/InvalidOperationExceptionSpec.php diff --git a/spec/Exception/InvalidOperationExceptionSpec.php b/spec/Exception/InvalidOperationExceptionSpec.php new file mode 100644 index 00000000..68bd34fb --- /dev/null +++ b/spec/Exception/InvalidOperationExceptionSpec.php @@ -0,0 +1,20 @@ +shouldHaveType(InvalidOperationException::class); + } + + function it_is_an_exception() + { + $this->shouldHaveType(Exception::class); + } +} diff --git a/src/Exception/InvalidOperationException.php b/src/Exception/InvalidOperationException.php index 479df357..16574d22 100644 --- a/src/Exception/InvalidOperationException.php +++ b/src/Exception/InvalidOperationException.php @@ -4,6 +4,10 @@ use Bernard\Exception; -class InvalidOperationException extends \Exception implements Exception +/** + * Thrown when someone tries to do an illegal operation on a queue + * (eg. enqueue a message when the queue is already closed) + */ +final class InvalidOperationException extends \Exception implements Exception { } diff --git a/tests/Exception/ExceptionTest.php b/tests/Exception/ExceptionTest.php index 30ec565d..3428aad4 100644 --- a/tests/Exception/ExceptionTest.php +++ b/tests/Exception/ExceptionTest.php @@ -27,7 +27,6 @@ public function testThrowException($exception, $base) public function exceptionProvider() { return [ - ['\Bernard\Exception\InvalidOperationException', '\Exception'], ['\Bernard\Exception\NotImplementedException', '\BadMethodCallException'], ['\Bernard\Exception\QueueNotFoundException', '\RuntimeException'], ['\Bernard\Exception\ReceiverNotFoundException', '\RuntimeException'], From d5066f2ca668fef5aa903ce66b6061c376a5903f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 08:13:14 +0100 Subject: [PATCH 037/108] Improve not implemented exception --- .../Exception/NotImplementedExceptionSpec.php | 20 +++++++++++++++++++ src/Exception/NotImplementedException.php | 2 +- tests/Exception/ExceptionTest.php | 1 - 3 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 spec/Exception/NotImplementedExceptionSpec.php diff --git a/spec/Exception/NotImplementedExceptionSpec.php b/spec/Exception/NotImplementedExceptionSpec.php new file mode 100644 index 00000000..5e824e42 --- /dev/null +++ b/spec/Exception/NotImplementedExceptionSpec.php @@ -0,0 +1,20 @@ +shouldHaveType(NotImplementedException::class); + } + + function it_is_an_exception() + { + $this->shouldHaveType(Exception::class); + } +} diff --git a/src/Exception/NotImplementedException.php b/src/Exception/NotImplementedException.php index d41826c6..7a315332 100644 --- a/src/Exception/NotImplementedException.php +++ b/src/Exception/NotImplementedException.php @@ -7,6 +7,6 @@ /** * Thrown when driver does not support requested feature. */ -class NotImplementedException extends \BadMethodCallException implements Exception +final class NotImplementedException extends \BadMethodCallException implements Exception { } diff --git a/tests/Exception/ExceptionTest.php b/tests/Exception/ExceptionTest.php index 3428aad4..fb9b638b 100644 --- a/tests/Exception/ExceptionTest.php +++ b/tests/Exception/ExceptionTest.php @@ -27,7 +27,6 @@ public function testThrowException($exception, $base) public function exceptionProvider() { return [ - ['\Bernard\Exception\NotImplementedException', '\BadMethodCallException'], ['\Bernard\Exception\QueueNotFoundException', '\RuntimeException'], ['\Bernard\Exception\ReceiverNotFoundException', '\RuntimeException'], ['\Bernard\Exception\ServiceUnavailableException', '\RuntimeException'], From 15b440f5340042fd43eb5d0e8fbc52f6dc54d236 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 08:14:18 +0100 Subject: [PATCH 038/108] Remove unused queue not found exception --- src/Exception/QueueNotFoundException.php | 12 ------------ tests/Exception/ExceptionTest.php | 1 - 2 files changed, 13 deletions(-) delete mode 100644 src/Exception/QueueNotFoundException.php diff --git a/src/Exception/QueueNotFoundException.php b/src/Exception/QueueNotFoundException.php deleted file mode 100644 index 9f39431e..00000000 --- a/src/Exception/QueueNotFoundException.php +++ /dev/null @@ -1,12 +0,0 @@ - Date: Sun, 18 Feb 2018 08:15:54 +0100 Subject: [PATCH 039/108] Improve receiver not found exception --- .../ReceiverNotFoundExceptionSpec.php | 20 +++++++++++++++++++ src/Exception/ReceiverNotFoundException.php | 5 ++--- tests/Exception/ExceptionTest.php | 1 - 3 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 spec/Exception/ReceiverNotFoundExceptionSpec.php diff --git a/spec/Exception/ReceiverNotFoundExceptionSpec.php b/spec/Exception/ReceiverNotFoundExceptionSpec.php new file mode 100644 index 00000000..ef38fe3c --- /dev/null +++ b/spec/Exception/ReceiverNotFoundExceptionSpec.php @@ -0,0 +1,20 @@ +shouldHaveType(ReceiverNotFoundException::class); + } + + function it_is_an_exception() + { + $this->shouldHaveType(Exception::class); + } +} diff --git a/src/Exception/ReceiverNotFoundException.php b/src/Exception/ReceiverNotFoundException.php index 2449d9a2..5878ff6f 100644 --- a/src/Exception/ReceiverNotFoundException.php +++ b/src/Exception/ReceiverNotFoundException.php @@ -5,9 +5,8 @@ use Bernard\Exception; /** - * Is thrown when a Router tries to map a Envelope to a receiver and - * cannot be done. + * Is thrown when a Router cannot map an Envelope to a receiver. */ -class ReceiverNotFoundException extends \RuntimeException implements Exception +final class ReceiverNotFoundException extends \RuntimeException implements Exception { } diff --git a/tests/Exception/ExceptionTest.php b/tests/Exception/ExceptionTest.php index 3be7b9ad..3933b0d1 100644 --- a/tests/Exception/ExceptionTest.php +++ b/tests/Exception/ExceptionTest.php @@ -27,7 +27,6 @@ public function testThrowException($exception, $base) public function exceptionProvider() { return [ - ['\Bernard\Exception\ReceiverNotFoundException', '\RuntimeException'], ['\Bernard\Exception\ServiceUnavailableException', '\RuntimeException'], ]; } From b65824a765218176b24152111bad9db9bc2495d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 08:20:35 +0100 Subject: [PATCH 040/108] Improve service unavailable exception --- .../ServiceUnavailableExceptionSpec.php | 20 +++++++++++++++++++ src/Exception/ServiceUnavailableException.php | 4 ++-- tests/Exception/ExceptionTest.php | 1 - 3 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 spec/Exception/ServiceUnavailableExceptionSpec.php diff --git a/spec/Exception/ServiceUnavailableExceptionSpec.php b/spec/Exception/ServiceUnavailableExceptionSpec.php new file mode 100644 index 00000000..76231b14 --- /dev/null +++ b/spec/Exception/ServiceUnavailableExceptionSpec.php @@ -0,0 +1,20 @@ +shouldHaveType(ServiceUnavailableException::class); + } + + function it_is_an_exception() + { + $this->shouldHaveType(Exception::class); + } +} diff --git a/src/Exception/ServiceUnavailableException.php b/src/Exception/ServiceUnavailableException.php index d84e82cf..ed06739a 100644 --- a/src/Exception/ServiceUnavailableException.php +++ b/src/Exception/ServiceUnavailableException.php @@ -5,8 +5,8 @@ use Bernard\Exception; /** - * Thrown when driver implementation is unavailable. + * Thrown when a service behind the driver implementation is unavailable. */ -class ServiceUnavailableException extends \RuntimeException implements Exception +final class ServiceUnavailableException extends \RuntimeException implements Exception { } diff --git a/tests/Exception/ExceptionTest.php b/tests/Exception/ExceptionTest.php index 3933b0d1..d86e2602 100644 --- a/tests/Exception/ExceptionTest.php +++ b/tests/Exception/ExceptionTest.php @@ -27,7 +27,6 @@ public function testThrowException($exception, $base) public function exceptionProvider() { return [ - ['\Bernard\Exception\ServiceUnavailableException', '\RuntimeException'], ]; } } From c1588fd7bdb127a0c645f537662f37822e3a0d59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 08:21:04 +0100 Subject: [PATCH 041/108] Remove unused exception test --- tests/Exception/ExceptionTest.php | 32 ------------------------------- 1 file changed, 32 deletions(-) delete mode 100644 tests/Exception/ExceptionTest.php diff --git a/tests/Exception/ExceptionTest.php b/tests/Exception/ExceptionTest.php deleted file mode 100644 index d86e2602..00000000 --- a/tests/Exception/ExceptionTest.php +++ /dev/null @@ -1,32 +0,0 @@ -assertInstanceOf(Exception::class, $e); - $this->assertInstanceOf($exception, $e); - $this->assertInstanceOf($base, $e); - - return; - } - - $this->fail('Exception not caught'); - } - - public function exceptionProvider() - { - return [ - ]; - } -} From 4db20265190922596cb0c8942685a765ccc3626a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 08:37:33 +0100 Subject: [PATCH 042/108] Fix unimported exception --- src/Router.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Router.php b/src/Router.php index 623128e1..65b8f5c2 100644 --- a/src/Router.php +++ b/src/Router.php @@ -2,6 +2,8 @@ namespace Bernard; +use Bernard\Exception\ReceiverNotFoundException; + interface Router { /** From 4343c06d1f251efe426e955ce909b6e48beb91ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 09:00:17 +0100 Subject: [PATCH 043/108] Add receiver interface --- spec/Receiver/CallableReceiverSpec.php | 37 +++++++++++++++++++++++++ src/Consumer.php | 4 +-- src/Receiver.php | 16 +++++++++++ src/Receiver/CallableReceiver.php | 26 ++++++++++++++++++ src/Router.php | 7 +++-- src/Router/SimpleRouter.php | 38 ++++++++++++++++++++++---- tests/Router/SimpleRouterTest.php | 11 ++++---- 7 files changed, 124 insertions(+), 15 deletions(-) create mode 100644 spec/Receiver/CallableReceiverSpec.php create mode 100644 src/Receiver.php create mode 100644 src/Receiver/CallableReceiver.php diff --git a/spec/Receiver/CallableReceiverSpec.php b/spec/Receiver/CallableReceiverSpec.php new file mode 100644 index 00000000..d458513a --- /dev/null +++ b/spec/Receiver/CallableReceiverSpec.php @@ -0,0 +1,37 @@ +beConstructedWith(function() {}); + } + + function it_is_initializable() + { + $this->shouldHaveType(CallableReceiver::class); + } + + function it_is_a_receiver() + { + $this->shouldHaveType(Receiver::class); + } + + function it_receives_a_message(Message $message) + { + $this->beConstructedWith(function(Message $message) { + $message->getName(); + }); + + $message->getName()->shouldBeCalled(); + + $this->receive($message); + } +} diff --git a/src/Consumer.php b/src/Consumer.php index b83e5853..15daa5b2 100644 --- a/src/Consumer.php +++ b/src/Consumer.php @@ -127,8 +127,8 @@ public function invoke(Envelope $envelope, Queue $queue) try { $this->dispatcher->dispatch(BernardEvents::INVOKE, new EnvelopeEvent($envelope, $queue)); - // for 5.3 support where a function name is not a callable - call_user_func($this->router->map($envelope), $envelope->getMessage()); + $receiver = $this->router->map($envelope); + $receiver->receive($envelope->getMessage()); // We successfully processed the message. $queue->acknowledge($envelope); diff --git a/src/Receiver.php b/src/Receiver.php new file mode 100644 index 00000000..56d9e921 --- /dev/null +++ b/src/Receiver.php @@ -0,0 +1,16 @@ +callable = $callable; + } + + /** + * {@inheritdoc} + */ + public function receive(Message $message) + { + call_user_func($this->callable, $message); + } +} diff --git a/src/Router.php b/src/Router.php index 65b8f5c2..16d60ba8 100644 --- a/src/Router.php +++ b/src/Router.php @@ -4,14 +4,17 @@ use Bernard\Exception\ReceiverNotFoundException; +/** + * Router is responsible for routing a message to it's receiver. + */ interface Router { /** - * Returns the right Receiver (callable) based on the Envelope. + * Returns the right Receiver based on the Envelope. * * @param Envelope $envelope * - * @return callable + * @return Receiver * * @throws ReceiverNotFoundException */ diff --git a/src/Router/SimpleRouter.php b/src/Router/SimpleRouter.php index 99973de4..4692bb16 100644 --- a/src/Router/SimpleRouter.php +++ b/src/Router/SimpleRouter.php @@ -4,6 +4,7 @@ use Bernard\Envelope; use Bernard\Exception\ReceiverNotFoundException; +use Bernard\Receiver; /** * Routes a Envelope to a Receiver by using the name of the Envelope. @@ -41,16 +42,13 @@ public function add($name, $receiver) public function map(Envelope $envelope) { $receiver = $this->get($envelope->getName()); + $receiver = $this->resolveReceiver($receiver, $envelope); if (null === $receiver) { throw new ReceiverNotFoundException(sprintf('No receiver found with name "%s".', $envelope->getName())); } - if (is_callable($receiver)) { - return $receiver; - } - - return [$receiver, lcfirst($envelope->getName())]; + return $receiver; } /** @@ -72,4 +70,34 @@ protected function get($name) { return isset($this->receivers[$name]) ? $this->receivers[$name] : null; } + + /** + * Resolves a receiver or returns null. + * + * @param mixed $receiver + * @param Envelope $envelope + * + * @return Receiver|null + */ + private function resolveReceiver($receiver, Envelope $envelope) + { + if (null === $receiver) { + return null; + } + + if ($receiver instanceof Receiver) { + return $receiver; + } + + if (is_callable($receiver) == false) { + $receiver = [$receiver, lcfirst($envelope->getName())]; + } + + // Receiver is still not a callable which means it's not a valid receiver. + if (is_callable($receiver) == false) { + return null; + } + + return new Receiver\CallableReceiver($receiver); + } } diff --git a/tests/Router/SimpleRouterTest.php b/tests/Router/SimpleRouterTest.php index 533a4325..b847c668 100644 --- a/tests/Router/SimpleRouterTest.php +++ b/tests/Router/SimpleRouterTest.php @@ -2,6 +2,7 @@ namespace Bernard\Tests; +use Bernard\Receiver; use Bernard\Router\SimpleRouter; use Bernard\Envelope; use Bernard\Message\PlainMessage; @@ -33,14 +34,14 @@ public function testThrowsExceptionWhenNothingMatches() public function testReceiversAreAddedThroughConstructor() { - $callable = function () {}; + $receiver = $this->prophesize(Receiver::class)->reveal(); $envelope = new Envelope(new PlainMessage('SendNewsletter')); $router = new SimpleRouter([ - 'SendNewsletter' => $callable, + 'SendNewsletter' => $receiver, ]); - $this->assertSame($callable, $router->map($envelope)); + $this->assertSame($receiver, $router->map($envelope)); } /** @@ -52,7 +53,7 @@ public function testItReturnsCallable($given, $expected) $envelope = new Envelope(new PlainMessage('SendNewsletter')); - $this->assertEquals($expected, $this->router->map($envelope)); + $this->assertInstanceOf(Receiver::class, $this->router->map($envelope)); } public function provideCallable() @@ -60,10 +61,8 @@ public function provideCallable() $callable = function () {}; return [ - ['Bernard\Tests\Fixtures\Service', ['Bernard\Tests\Fixtures\Service', 'sendNewsletter']], ['var_dump', 'var_dump'], [$callable, $callable], - [new \stdClass(), [new \stdClass(), 'sendNewsletter']], ]; } } From fa4b9c51e266cf11bc46f031f2611058f1516afe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 09:25:56 +0100 Subject: [PATCH 044/108] Make SimpleRouter immutable --- src/Router/SimpleRouter.php | 7 +- tests/ConsumerTest.php | 117 ++++++++++++++++++++---------- tests/Fixtures/Service.php | 29 -------- tests/Router/SimpleRouterTest.php | 8 +- 4 files changed, 87 insertions(+), 74 deletions(-) delete mode 100644 tests/Fixtures/Service.php diff --git a/src/Router/SimpleRouter.php b/src/Router/SimpleRouter.php index 4692bb16..490f8b89 100644 --- a/src/Router/SimpleRouter.php +++ b/src/Router/SimpleRouter.php @@ -5,11 +5,12 @@ use Bernard\Envelope; use Bernard\Exception\ReceiverNotFoundException; use Bernard\Receiver; +use Bernard\Router; /** - * Routes a Envelope to a Receiver by using the name of the Envelope. + * Routes an Envelope to a Receiver by using the name of the Envelope. */ -class SimpleRouter implements \Bernard\Router +class SimpleRouter implements Router { protected $receivers = []; @@ -27,7 +28,7 @@ public function __construct(array $receivers = []) * @param string $name * @param mixed $receiver */ - public function add($name, $receiver) + private function add($name, $receiver) { if (!$this->accepts($receiver)) { throw new \InvalidArgumentException(sprintf('Given "%s" is not supported.', $receiver)); diff --git a/tests/ConsumerTest.php b/tests/ConsumerTest.php index feba12c7..8d0c4dd7 100644 --- a/tests/ConsumerTest.php +++ b/tests/ConsumerTest.php @@ -3,18 +3,21 @@ namespace Bernard\Tests; use Bernard\Consumer; +use Bernard\Exception\ReceiverNotFoundException; use Bernard\Queue\InMemoryQueue; use Bernard\Envelope; use Bernard\Message\PlainMessage; -use Bernard\Router\SimpleRouter; +use Bernard\Receiver; +use Bernard\Router; use Bernard\Event\RejectEnvelopeEvent; use Bernard\Event\EnvelopeEvent; use Bernard\Event\PingEvent; +use Prophecy\Prophecy\ObjectProphecy; class ConsumerTest extends \PHPUnit\Framework\TestCase { /** - * @var SimpleRouter + * @var Router|ObjectProphecy */ private $router; @@ -30,20 +33,26 @@ class ConsumerTest extends \PHPUnit\Framework\TestCase public function setUp() { - $this->router = new SimpleRouter(); - $this->router->add('ImportUsers', new Fixtures\Service()); + $this->router = $this->prophesize(Router::class); $this->dispatcher = $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); - $this->consumer = new Consumer($this->router, $this->dispatcher); + + $this->consumer = new Consumer($this->router->reveal(), $this->dispatcher); } public function testEmitsConsumeEvent() { - $envelope = new Envelope(new PlainMessage('ImportUsers')); + $envelope = new Envelope($message = new PlainMessage('ImportUsers')); + $queue = $this->getMockBuilder('Bernard\Queue\InMemoryQueue')->setMethods([ 'dequeue', ])->setConstructorArgs(['queue'])->getMock(); + /** @var Receiver|ObjectProphecy $receiver */ + $receiver = $this->prophesize(Receiver::class); + $receiver->receive($message)->shouldBeCalled(); + $this->router->map($envelope)->willReturn($receiver); + $queue->expects($this->once()) ->method('dequeue') ->willReturn($envelope); @@ -64,13 +73,14 @@ public function testEmitsExceptionEvent() { $exception = new \InvalidArgumentException(); - $this->router->add('ImportUsers', function () use ($exception) { - throw $exception; - }); - - $envelope = new Envelope(new PlainMessage('ImportUsers')); + $envelope = new Envelope($message = new PlainMessage('ImportUsers')); $queue = new InMemoryQueue('queue'); + /** @var Receiver|ObjectProphecy $receiver */ + $receiver = $this->prophesize(Receiver::class); + $receiver->receive($message)->willThrow($exception); + $this->router->map($envelope)->willReturn($receiver); + $this->dispatcher->expects($this->at(1))->method('dispatch') ->with('bernard.reject', new RejectEnvelopeEvent($envelope, $queue, $exception)); @@ -88,22 +98,22 @@ public function testShutdown() public function testPauseResume() { - $service = new Fixtures\Service(); - - $this->router->add('ImportUsers', $service); - + $envelope = new Envelope($message = new PlainMessage('ImportUsers')); $queue = new InMemoryQueue('queue'); - $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); + $queue->enqueue($envelope); + + /** @var Receiver|ObjectProphecy $receiver */ + $receiver = $this->prophesize(Receiver::class); + $receiver->receive($message)->shouldBeCalled(); + $this->router->map($envelope)->willReturn($receiver); $this->consumer->pause(); $this->assertTrue($this->consumer->tick($queue)); - $this->assertFalse($service->importUsers); $this->consumer->resume(); $this->assertTrue($this->consumer->tick($queue)); - $this->assertTrue($service->importUsers); } public function testMaxRuntime() @@ -123,28 +133,39 @@ public function testNoEnvelopeInQueue() public function testEnvelopeIsAcknowledged() { - $service = new Fixtures\Service(); - $envelope = new Envelope(new PlainMessage('ImportUsers')); + $envelope = new Envelope($message = new PlainMessage('ImportUsers')); - $this->router->add('ImportUsers', $service); + /** @var Receiver|ObjectProphecy $receiver */ + $receiver = $this->prophesize(Receiver::class); + $receiver->receive($message)->shouldBeCalled(); + $this->router->map($envelope)->willReturn($receiver); $queue = $this->createMock('Bernard\Queue'); $queue->expects($this->once())->method('dequeue')->will($this->returnValue($envelope)); $queue->expects($this->once())->method('acknowledge')->with($this->equalTo($envelope)); $this->consumer->tick($queue); - - $this->assertTrue($service->importUsers); } public function testMaxMessages() { - $this->router->add('ImportUsers', new Fixtures\Service()); + $envelope1 = new Envelope($message1 = new PlainMessage('ImportUsers')); + $envelope2 = new Envelope($message2 = new PlainMessage('ImportUsers')); + $envelope3 = new Envelope($message3 = new PlainMessage('ImportUsers')); $queue = new InMemoryQueue('send-newsletter'); - $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); - $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); - $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); + $queue->enqueue($envelope1); + $queue->enqueue($envelope2); + $queue->enqueue($envelope3); + + /** @var Receiver|ObjectProphecy $receiver */ + $receiver = $this->prophesize(Receiver::class); + $receiver->receive($message1)->shouldBeCalled(); + $receiver->receive($message2)->shouldBeCalled(); + $receiver->receive($message3)->shouldBeCalled(); + $this->router->map($envelope1)->willReturn($receiver); + $this->router->map($envelope2)->willReturn($receiver); + $this->router->map($envelope3)->willReturn($receiver); $this->assertFalse($this->consumer->tick($queue, ['max-messages' => 1])); $this->assertTrue($this->consumer->tick($queue)); @@ -153,11 +174,19 @@ public function testMaxMessages() public function testStopAfterLastMessage() { - $this->router->add('ImportUsers', new Fixtures\Service()); + $envelope1 = new Envelope($message1 = new PlainMessage('ImportUsers')); + $envelope2 = new Envelope($message2 = new PlainMessage('ImportUsers')); $queue = new InMemoryQueue('send-newsletter'); - $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); - $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); + $queue->enqueue($envelope1); + $queue->enqueue($envelope2); + + /** @var Receiver|ObjectProphecy $receiver */ + $receiver = $this->prophesize(Receiver::class); + $receiver->receive($message1)->shouldBeCalled(); + $receiver->receive($message2)->shouldBeCalled(); + $this->router->map($envelope1)->willReturn($receiver); + $this->router->map($envelope2)->willReturn($receiver); $this->assertTrue($this->consumer->tick($queue, ['stop-when-empty' => true])); $this->assertTrue($this->consumer->tick($queue, ['stop-when-empty' => true])); @@ -169,10 +198,12 @@ public function testStopAfterLastMessage() */ public function testStopOnError() { - $this->router->add('ImportUsers', new Fixtures\Service()); + $envelope = new Envelope($message = new PlainMessage('DifferentMessageKey')); $queue = new InMemoryQueue('send-newsletter'); - $queue->enqueue(new Envelope(new PlainMessage('DifferentMessageKey'))); + $queue->enqueue($envelope); + + $this->router->map($envelope)->willThrow(ReceiverNotFoundException::class); $this->consumer->tick($queue, ['stop-on-error' => true]); @@ -184,16 +215,17 @@ public function testStopOnError() */ public function testEnvelopeWillBeInvoked() { - $service = new Fixtures\Service(); - - $this->router->add('ImportUsers', $service); + $envelope = new Envelope($message = new PlainMessage('ImportUsers')); $queue = new InMemoryQueue('send-newsletter'); - $queue->enqueue(new Envelope(new PlainMessage('ImportUsers'))); + $queue->enqueue($envelope); - $this->consumer->tick($queue); + /** @var Receiver|ObjectProphecy $receiver */ + $receiver = $this->prophesize(Receiver::class); + $receiver->receive($message)->shouldBeCalled(); + $this->router->map($envelope)->willReturn($receiver); - $this->assertTrue($service->importUsers); + $this->consumer->tick($queue); } /** @@ -202,10 +234,15 @@ public function testEnvelopeWillBeInvoked() */ public function testWillRejectDispatchOnThrowableError() { - $this->router->add('ImportReport', new Fixtures\Service()); + $envelope = new Envelope($message = new PlainMessage('ImportReport')); $queue = new InMemoryQueue('send-newsletter'); - $queue->enqueue(new Envelope(new PlainMessage('ImportReport'))); + $queue->enqueue($envelope); + + /** @var Receiver|ObjectProphecy $receiver */ + $receiver = $this->prophesize(Receiver::class); + $receiver->receive($message)->willThrow(\TypeError::class); + $this->router->map($envelope)->willReturn($receiver); $this->dispatcher->expects(self::at(0))->method('dispatch')->with('bernard.ping'); $this->dispatcher->expects(self::at(1))->method('dispatch')->with('bernard.invoke'); diff --git a/tests/Fixtures/Service.php b/tests/Fixtures/Service.php deleted file mode 100644 index b259c23d..00000000 --- a/tests/Fixtures/Service.php +++ /dev/null @@ -1,29 +0,0 @@ -importUsers = true; - } - - public function createFile() - { - touch(__DIR__.'/create_file.test'); - } - - public function importReport(Report $report) - { - // note: the class hinted on this method does not exist on purpose, as calling this method should cause a - // Throwable to be thrown - } -} diff --git a/tests/Router/SimpleRouterTest.php b/tests/Router/SimpleRouterTest.php index b847c668..f1a87765 100644 --- a/tests/Router/SimpleRouterTest.php +++ b/tests/Router/SimpleRouterTest.php @@ -19,7 +19,9 @@ public function setUp() */ public function testThrowsExceptionWhenReceiverIsNotSupported() { - $this->router->add('SendNewsletter', 1); + $this->router = new SimpleRouter([ + 'SendNewsletter' => 1, + ]); } /** @@ -49,7 +51,9 @@ public function testReceiversAreAddedThroughConstructor() */ public function testItReturnsCallable($given, $expected) { - $this->router->add('SendNewsletter', $given); + $this->router = new SimpleRouter([ + 'SendNewsletter' => $given, + ]); $envelope = new Envelope(new PlainMessage('SendNewsletter')); From bee3b972745edbbb14162b3770d3e8d30412a81e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 09:47:05 +0100 Subject: [PATCH 045/108] Improve the class name router --- spec/Router/ClassNameRouterSpec.php | 29 +++++++++++++++++++---------- src/Router/ClassNameRouter.php | 29 +++++++++++++---------------- src/Router/SimpleRouter.php | 16 ++++++++++++++-- 3 files changed, 46 insertions(+), 28 deletions(-) diff --git a/spec/Router/ClassNameRouterSpec.php b/spec/Router/ClassNameRouterSpec.php index 2a936ecb..e94dd821 100644 --- a/spec/Router/ClassNameRouterSpec.php +++ b/spec/Router/ClassNameRouterSpec.php @@ -5,19 +5,13 @@ use Bernard\Envelope; use Bernard\Exception\ReceiverNotFoundException; use Bernard\Message; +use Bernard\Receiver; use Bernard\Router; use Bernard\Router\ClassNameRouter; use PhpSpec\ObjectBehavior; class ClassNameRouterSpec extends ObjectBehavior { - function let() - { - $this->beConstructedWith([ - Message\PlainMessage::class => function() {}, - ]); - } - function it_is_initializable() { $this->shouldHaveType(ClassNameRouter::class); @@ -28,11 +22,26 @@ function it_is_a_router() $this->shouldImplement(Router::class); } - function it_maps_an_envelope() + function it_maps_an_envelope(Message $message) { - $envelope = new Envelope(new Message\PlainMessage('SendNewsletter')); + $this->beConstructedWith([ + get_class($message->getWrappedObject()) => function() {}, + ]); + + $envelope = new Envelope($message->getWrappedObject()); + + $this->map($envelope)->shouldImplement(Receiver::class); + } + + function it_maps_an_envelope_to_a_message_parent(Message $message) + { + $this->beConstructedWith([ + Message::class => function() {}, + ]); + + $envelope = new Envelope($message->getWrappedObject()); - $this->map($envelope)->shouldBeCallable(); + $this->map($envelope)->shouldImplement(Receiver::class); } function it_throws_an_exception_when_envelope_cannot_be_mapped(Message $message) diff --git a/src/Router/ClassNameRouter.php b/src/Router/ClassNameRouter.php index a791972f..50c2de44 100644 --- a/src/Router/ClassNameRouter.php +++ b/src/Router/ClassNameRouter.php @@ -3,24 +3,13 @@ namespace Bernard\Router; use Bernard\Envelope; -use Bernard\Exception\ReceiverNotFoundException; -class ClassNameRouter extends SimpleRouter +/** + * Uses the message class name as the message name. + * Allows registering catch-all receivers for message parent types. + */ +final class ClassNameRouter extends SimpleRouter { - /** - * {@inheritdoc} - */ - public function map(Envelope $envelope) - { - $receiver = $this->get($envelope->getClass()); - - if (!is_callable($receiver)) { - throw new ReceiverNotFoundException(sprintf('No receiver found for class "%s".', $envelope->getClass())); - } - - return $receiver; - } - /** * {@inheritdoc} */ @@ -34,4 +23,12 @@ protected function get($name) return null; } + + /** + * {@inheritdoc} + */ + protected function getName(Envelope $envelope) + { + return $envelope->getClass(); + } } diff --git a/src/Router/SimpleRouter.php b/src/Router/SimpleRouter.php index 490f8b89..bfd0af74 100644 --- a/src/Router/SimpleRouter.php +++ b/src/Router/SimpleRouter.php @@ -8,7 +8,7 @@ use Bernard\Router; /** - * Routes an Envelope to a Receiver by using the name of the Envelope. + * Routes an Envelope to a Receiver by an internal receiver map. */ class SimpleRouter implements Router { @@ -42,7 +42,7 @@ private function add($name, $receiver) */ public function map(Envelope $envelope) { - $receiver = $this->get($envelope->getName()); + $receiver = $this->get($this->getName($envelope)); $receiver = $this->resolveReceiver($receiver, $envelope); if (null === $receiver) { @@ -72,6 +72,18 @@ protected function get($name) return isset($this->receivers[$name]) ? $this->receivers[$name] : null; } + /** + * Returns the (message) name to look for in the receiver map. + * + * @param Envelope $envelope + * + * @return string + */ + protected function getName(Envelope $envelope) + { + return $envelope->getName(); + } + /** * Resolves a receiver or returns null. * From 0764ccf7cc0a674d4c463d5e00b33e1a687bce3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 11:45:08 +0100 Subject: [PATCH 046/108] Add ReceiverResolver concept, replace container router --- composer.json | 5 +- doc/consuming.rst | 105 ++++++++++++---- example/bootstrap.php | 4 +- spec/Router/ClassNameRouterSpec.php | 61 +++++++-- .../Router/ContainerNotFoundExceptionStub.php | 7 ++ spec/Router/ContainerReceiverResolverSpec.php | 81 ++++++++++++ spec/Router/ContainerRouterSpec.php | 63 ---------- spec/Router/ReceiverMapRouterSpec.php | 74 +++++++++++ spec/Router/ReceiverStub.php | 16 +++ spec/Router/SimpleReceiverResolverSpec.php | 77 ++++++++++++ src/Receiver/CallableReceiver.php | 1 + src/Router/ClassNameRouter.php | 2 +- src/Router/ContainerReceiverResolver.php | 45 +++++++ src/Router/ContainerRouter.php | 48 -------- src/Router/ReceiverMapRouter.php | 84 +++++++++++++ src/Router/ReceiverResolver.php | 31 +++++ src/Router/SimpleReceiverResolver.php | 45 +++++++ src/Router/SimpleRouter.php | 116 ------------------ tests/Router/SimpleRouterTest.php | 72 ----------- 19 files changed, 601 insertions(+), 336 deletions(-) create mode 100644 spec/Router/ContainerNotFoundExceptionStub.php create mode 100644 spec/Router/ContainerReceiverResolverSpec.php delete mode 100644 spec/Router/ContainerRouterSpec.php create mode 100644 spec/Router/ReceiverMapRouterSpec.php create mode 100644 spec/Router/ReceiverStub.php create mode 100644 spec/Router/SimpleReceiverResolverSpec.php create mode 100644 src/Router/ContainerReceiverResolver.php delete mode 100644 src/Router/ContainerRouter.php create mode 100644 src/Router/ReceiverMapRouter.php create mode 100644 src/Router/ReceiverResolver.php create mode 100644 src/Router/SimpleReceiverResolver.php delete mode 100644 src/Router/SimpleRouter.php delete mode 100644 tests/Router/SimpleRouterTest.php diff --git a/composer.json b/composer.json index 9fdcaf7a..e93c65d4 100644 --- a/composer.json +++ b/composer.json @@ -44,7 +44,10 @@ "psr-4" : { "Bernard\\" : "src/" } }, "autoload-dev" : { - "psr-4" : { "Bernard\\Tests\\" : "tests/" } + "psr-4" : { + "Bernard\\Tests\\" : "tests/", + "spec\\Bernard\\" : "spec/" + } }, "scripts": { "test": [ diff --git a/doc/consuming.rst b/doc/consuming.rst index 877c8bcb..316c2262 100644 --- a/doc/consuming.rst +++ b/doc/consuming.rst @@ -1,34 +1,21 @@ Consuming Messages ================== -A single message represents a job that needs to be performed, and as described -earlier, a message's name is used to determine which service object should -receive that message. +Consuming messages has two requirements: + +* the system needs to know how messages should be handled +* the system needs to provide extension points for certain events -A service object can be any object that has a method corresponding to the name of the -message with the first letter lower cased. So ``new PlainMessage('SendNewsletter')`` will trigger a -call to ``$serviceObject->sendNewsletter($message)``. For the system to know which service -object should handle which messages, you are required to register them first. +The first requirement is fulfilled by message routing, the second is by the event dispatcher system. .. code-block:: php add('SendNewsletter', new NewsletterMessageHandler); + use Symfony\Component\EventDispatcher\EventDispatcher; - // Bernard also comes with a router for PSR-11 container which allows you - // to use service ids and have your service object lazy loader. - // - // $router = new \Bernard\Router\ContainerRouter($container); - // $router->add('SendNewsletter', 'my.service.id'); + // $router = see bellow + $eventDispatcher = new EventDispatcher(); // Create a Consumer and start the loop. $consumer = new Consumer($router, $eventDispatcher); @@ -40,6 +27,82 @@ object should handle which messages, you are required to register them first. 'max-runtime' => 900, )); + +Routing +------- + +A single message represents a job that needs to be performed, and as described +earlier, by default a message's name is used to determine which receiver should +receive that message. + +A receiver can be any of the following: + +* callable +* class with a static method with the name of the message with the first letter lower cased +* object with a method with the name of the message with the first letter lower cased +* object implementing the ``Bernard\Receiver`` interface + + +For the system to know which receiver should handle which messages, you are required to register them first. + +.. code-block:: php + + new NewsletterMessageHandler(), + ]); + + +Message routing can also happen based on the message class instead of the message name. + +.. code-block:: php + + new NewsletterMessageHandler(), + ]); + + +In some cases the above described receiver rules might not be enough. +The provided router implementations also accept a receiver resolver which can be used for example to resolve +receivers from a Dependency Injection container. A good example for that is the PSR-11 container resolver +implementation that comes with this package. + +.. code-block:: php + + NewsletterMessageHandler::class, + ], + new ContainerReceiverResolver($container), + ); + + Commandline Interface --------------------- diff --git a/example/bootstrap.php b/example/bootstrap.php index c2177c4a..58f3b212 100644 --- a/example/bootstrap.php +++ b/example/bootstrap.php @@ -5,7 +5,7 @@ use Bernard\Message; use Bernard\Producer; use Bernard\QueueFactory\PersistentFactory; -use Bernard\Router\SimpleRouter; +use Bernard\Router\ReceiverMapRouter; use Bernard\Serializer; use Symfony\Component\EventDispatcher\EventDispatcher; @@ -50,7 +50,7 @@ function get_producer() function get_receivers() { - return new SimpleRouter([ + return new ReceiverMapRouter([ 'EchoTime' => new EchoTimeService(), ]); } diff --git a/spec/Router/ClassNameRouterSpec.php b/spec/Router/ClassNameRouterSpec.php index e94dd821..0c565849 100644 --- a/spec/Router/ClassNameRouterSpec.php +++ b/spec/Router/ClassNameRouterSpec.php @@ -22,32 +22,69 @@ function it_is_a_router() $this->shouldImplement(Router::class); } - function it_maps_an_envelope(Message $message) + function it_routes_an_envelope_to_a_receiver(Message $message, Router\ReceiverResolver $receiverResolver, Receiver $receiver) { - $this->beConstructedWith([ - get_class($message->getWrappedObject()) => function() {}, - ]); + $envelope = new Envelope($message->getWrappedObject()); + + $receiverResolver->accepts('receiver')->willReturn(true); + $receiverResolver->resolve('receiver', $envelope)->willReturn($receiver); + + $this->beConstructedWith( + [ + get_class($message->getWrappedObject()) => 'receiver', + ], + $receiverResolver + ); + $this->map($envelope)->shouldReturn($receiver); + } + + function it_routes_an_envelope_to_a_receiver_based_on_message_parent(Message $message, Router\ReceiverResolver $receiverResolver, Receiver $receiver) + { $envelope = new Envelope($message->getWrappedObject()); - $this->map($envelope)->shouldImplement(Receiver::class); + $receiverResolver->accepts('receiver')->willReturn(true); + $receiverResolver->resolve('receiver', $envelope)->willReturn($receiver); + + $this->beConstructedWith( + [ + Message::class => 'receiver', + ], + $receiverResolver + ); + + $this->map($envelope)->shouldReturn($receiver); } - function it_maps_an_envelope_to_a_message_parent(Message $message) + function it_throws_an_exception_when_a_receiver_is_not_accepted(Router\ReceiverResolver $receiverResolver) { - $this->beConstructedWith([ - Message::class => function() {}, - ]); + $receiverResolver->accepts('receiver')->willReturn(false); - $envelope = new Envelope($message->getWrappedObject()); + $this->beConstructedWith( + [ + Message::class => 'receiver', + ], + $receiverResolver + ); - $this->map($envelope)->shouldImplement(Receiver::class); + $this->shouldThrow(\InvalidArgumentException::class)->duringInstantiation(); } - function it_throws_an_exception_when_envelope_cannot_be_mapped(Message $message) + function it_throws_an_exception_when_an_envelop_cannot_be_routed_to_a_receiver(Message $message, Router\ReceiverResolver $receiverResolver) { + $message->getName()->willReturn('message'); $envelope = new Envelope($message->getWrappedObject()); + $receiverResolver->accepts('receiver')->willReturn(true); + $receiverResolver->resolve('receiver', $envelope)->willReturn(null); + + $this->beConstructedWith( + [ + get_class($message->getWrappedObject()) => 'receiver', + ], + $receiverResolver + ); + $this->shouldThrow(ReceiverNotFoundException::class)->duringMap($envelope); } } diff --git a/spec/Router/ContainerNotFoundExceptionStub.php b/spec/Router/ContainerNotFoundExceptionStub.php new file mode 100644 index 00000000..af023fa8 --- /dev/null +++ b/spec/Router/ContainerNotFoundExceptionStub.php @@ -0,0 +1,7 @@ +beConstructedWith($container); + } + + function it_is_initializable() + { + $this->shouldHaveType(ContainerReceiverResolver::class); + } + + function it_is_a_receiver_resolver() + { + $this->shouldHaveType(ReceiverResolver::class); + } + + function it_accepts_a_service_receiver(ContainerInterface $container) + { + $container->has('my.service')->willReturn(true); + + $this->accepts('my.service')->shouldReturn(true); + } + + function it_returns_null_when_the_service_is_not_found(Message $message, ContainerInterface $container) + { + $container->get('my.service')->willThrow(ContainerNotFoundExceptionStub::class); + + $this->resolve('my.service', new Envelope($message->getWrappedObject()))->shouldReturn(null); + } + + function it_returns_the_receiver_when_it_is_already_a_receiver(Message $message, Receiver $receiver, ContainerInterface $container) + { + $container->get('my.service')->willReturn($receiver); + + $this->resolve('my.service', new Envelope($message->getWrappedObject()))->shouldReturn($receiver); + } + + function it_returns_a_callable_receiver_when_the_receiver_is_callable(Message $message, ContainerInterface $container) + { + $container->get('my.service')->willReturn(function(Message $message) {}); + + $this->resolve('my.service', new Envelope($message->getWrappedObject()))->shouldHaveType(Receiver\CallableReceiver::class); + } + + function it_returns_a_callable_receiver_when_the_receiver_class_has_a_static_method_for_the_message(Message $message, ContainerInterface $container) + { + $container->get('my.service')->willReturn(ReceiverStub::class); + $message->getName()->willReturn('StaticMessageName'); + + $this->resolve('my.service', new Envelope($message->getWrappedObject()))->shouldHaveType(Receiver\CallableReceiver::class); + } + + function it_returns_a_callable_receiver_when_the_receiver_object_has_a_method_for_the_message(Message $message, ContainerInterface $container) + { + $container->get('my.service')->willReturn(new ReceiverStub()); + $message->getName()->willReturn('MessageName'); + + $this->resolve('my.service', new Envelope($message->getWrappedObject()))->shouldHaveType(Receiver\CallableReceiver::class); + } + + function it_returns_a_callable_receiver_when_the_receiver_object_has_a_static_method_for_the_message(Message $message, ContainerInterface $container) + { + $container->get('my.service')->willReturn(new ReceiverStub()); + $message->getName()->willReturn('StaticMessageName'); + + $this->resolve('my.service', new Envelope($message->getWrappedObject()))->shouldHaveType(Receiver\CallableReceiver::class); + } +} diff --git a/spec/Router/ContainerRouterSpec.php b/spec/Router/ContainerRouterSpec.php deleted file mode 100644 index 48ef9ad9..00000000 --- a/spec/Router/ContainerRouterSpec.php +++ /dev/null @@ -1,63 +0,0 @@ -beConstructedWith($container); - } - - function it_is_initializable() - { - $this->shouldHaveType(ContainerRouter::class); - } - - function it_is_a_router() - { - $this->shouldImplement(Router::class); - } - - function it_maps_an_envelope(Message $message, ContainerInterface $container) - { - $this->beConstructedWith( - $container, - [ - 'message' => 'my.service', - ] - ); - - $message->getName()->willReturn('message'); - - $container->has('my.service')->willReturn(true); - $container->get('my.service')->willReturn(function () {}); - - $envelope = new Envelope($message->getWrappedObject()); - - $this->map($envelope)->shouldBeCallable(); - } - - function it_throws_an_exception_when_envelope_cannot_be_mapped(Message $message, ContainerInterface $container) - { - $message->getName()->willReturn('message'); - - $container->has('my.service')->willReturn(true); - $container->get('my.service')->willThrow(NotFoundException::class); - - $envelope = new Envelope($message->getWrappedObject()); - - $this->shouldThrow(ReceiverNotFoundException::class)->duringMap($envelope); - } -} diff --git a/spec/Router/ReceiverMapRouterSpec.php b/spec/Router/ReceiverMapRouterSpec.php new file mode 100644 index 00000000..c0fdf63d --- /dev/null +++ b/spec/Router/ReceiverMapRouterSpec.php @@ -0,0 +1,74 @@ +shouldHaveType(ReceiverMapRouter::class); + } + + function it_is_a_router() + { + $this->shouldImplement(Router::class); + } + + function it_routes_an_envelope_to_a_receiver(Message $message, Router\ReceiverResolver $receiverResolver, Receiver $receiver) + { + $message->getName()->willReturn('message'); + $envelope = new Envelope($message->getWrappedObject()); + + $receiverResolver->accepts('receiver')->willReturn(true); + $receiverResolver->resolve('receiver', $envelope)->willReturn($receiver); + + $this->beConstructedWith( + [ + 'message' => 'receiver', + ], + $receiverResolver + ); + + $this->map($envelope)->shouldReturn($receiver); + } + + function it_throws_an_exception_when_a_receiver_is_not_accepted(Router\ReceiverResolver $receiverResolver) + { + $receiverResolver->accepts('receiver')->willReturn(false); + + $this->beConstructedWith( + [ + 'message' => 'receiver', + ], + $receiverResolver + ); + + $this->shouldThrow(\InvalidArgumentException::class)->duringInstantiation(); + } + + function it_throws_an_exception_when_an_envelop_cannot_be_routed_to_a_receiver(Message $message, Router\ReceiverResolver $receiverResolver) + { + $message->getName()->willReturn('message'); + $envelope = new Envelope($message->getWrappedObject()); + + $receiverResolver->accepts('receiver')->willReturn(true); + $receiverResolver->resolve('receiver', $envelope)->willReturn(null); + + $this->beConstructedWith( + [ + 'message' => 'receiver', + ], + $receiverResolver + ); + + $this->shouldThrow(ReceiverNotFoundException::class)->duringMap($envelope); + } +} diff --git a/spec/Router/ReceiverStub.php b/spec/Router/ReceiverStub.php new file mode 100644 index 00000000..27205d01 --- /dev/null +++ b/spec/Router/ReceiverStub.php @@ -0,0 +1,16 @@ +shouldHaveType(SimpleReceiverResolver::class); + } + + function it_is_a_receiver_resolver() + { + $this->shouldHaveType(ReceiverResolver::class); + } + + function it_accepts_a_callable_receiver() + { + $callable = function(Message $message) {}; + + $this->accepts($callable)->shouldReturn(true); + } + + function it_accepts_a_class_receiver() + { + $this->accepts(ReceiverStub::class)->shouldReturn(true); + } + + function it_accepts_an_object_receiver() + { + $this->accepts(new ReceiverStub())->shouldReturn(true); + } + + function it_returns_null_when_the_receiver_is_null(Message $message) + { + $this->resolve(null, new Envelope($message->getWrappedObject()))->shouldReturn(null); + } + + function it_returns_the_receiver_when_it_is_already_a_receiver(Message $message, Receiver $receiver) + { + $this->resolve($receiver, new Envelope($message->getWrappedObject()))->shouldReturn($receiver); + } + + function it_returns_a_callable_receiver_when_the_receiver_is_callable(Message $message) + { + $callable = function(Message $message) {}; + $this->resolve($callable, new Envelope($message->getWrappedObject()))->shouldHaveType(Receiver\CallableReceiver::class); + } + + function it_returns_a_callable_receiver_when_the_receiver_class_has_a_static_method_for_the_message(Message $message) + { + $message->getName()->willReturn('StaticMessageName'); + + $this->resolve(ReceiverStub::class, new Envelope($message->getWrappedObject()))->shouldHaveType(Receiver\CallableReceiver::class); + } + + function it_returns_a_callable_receiver_when_the_receiver_object_has_a_method_for_the_message(Message $message) + { + $message->getName()->willReturn('MessageName'); + + $this->resolve(new ReceiverStub(), new Envelope($message->getWrappedObject()))->shouldHaveType(Receiver\CallableReceiver::class); + } + + function it_returns_a_callable_receiver_when_the_receiver_object_has_a_static_method_for_the_message(Message $message) + { + $message->getName()->willReturn('StaticMessageName'); + + $this->resolve(new ReceiverStub(), new Envelope($message->getWrappedObject()))->shouldHaveType(Receiver\CallableReceiver::class); + } +} diff --git a/src/Receiver/CallableReceiver.php b/src/Receiver/CallableReceiver.php index 2ebd5b2b..9034753f 100644 --- a/src/Receiver/CallableReceiver.php +++ b/src/Receiver/CallableReceiver.php @@ -1,6 +1,7 @@ container = $container; + } + + /** + * {@inheritdoc} + */ + public function accepts($receiver) + { + return $this->container->has($receiver); + } + + /** + * {@inheritdoc} + */ + public function resolve($receiver, Envelope $envelope) + { + try { + $receiver = $this->container->get($receiver); + } catch (NotFoundExceptionInterface $e) { + return null; + } + + return parent::resolve($receiver, $envelope); + } +} diff --git a/src/Router/ContainerRouter.php b/src/Router/ContainerRouter.php deleted file mode 100644 index c43e30ea..00000000 --- a/src/Router/ContainerRouter.php +++ /dev/null @@ -1,48 +0,0 @@ -container = $container; - - parent::__construct($receivers); - } - - /** - * {@inheritdoc} - */ - protected function get($name) - { - $serviceId = parent::get($name); - $serviceId = $serviceId ?: ''; - - try { - return $this->container->get($serviceId); - } catch (NotFoundExceptionInterface $e) { - return null; - } - } - - /** - * {@inheritdoc} - */ - protected function accepts($receiver) - { - return $this->container->has($receiver); - } -} diff --git a/src/Router/ReceiverMapRouter.php b/src/Router/ReceiverMapRouter.php new file mode 100644 index 00000000..4e2a38c3 --- /dev/null +++ b/src/Router/ReceiverMapRouter.php @@ -0,0 +1,84 @@ +receiverResolver = $receiverResolver; + + foreach ($receivers as $name => $receiver) { + $this->add($name, $receiver); + } + } + + /** + * @param string $name + * @param mixed $receiver + */ + private function add($name, $receiver) + { + if (!$this->receiverResolver->accepts($receiver)) { + throw new \InvalidArgumentException(sprintf('Receiver "%s" is not supported.', $receiver)); + } + + $this->receivers[$name] = $receiver; + } + + /** + * {@inheritdoc} + */ + public function map(Envelope $envelope) + { + $receiver = $this->get($this->getName($envelope)); + $receiver = $this->receiverResolver->resolve($receiver, $envelope); + + if (null === $receiver) { + throw new ReceiverNotFoundException(sprintf('No receiver found with name "%s".', $envelope->getName())); + } + + return $receiver; + } + + /** + * @param string $name + * + * @return mixed + */ + protected function get($name) + { + return isset($this->receivers[$name]) ? $this->receivers[$name] : null; + } + + /** + * Returns the (message) name to look for in the receiver map. + * + * @param Envelope $envelope + * + * @return string + */ + protected function getName(Envelope $envelope) + { + return $envelope->getName(); + } +} diff --git a/src/Router/ReceiverResolver.php b/src/Router/ReceiverResolver.php new file mode 100644 index 00000000..baee3e42 --- /dev/null +++ b/src/Router/ReceiverResolver.php @@ -0,0 +1,31 @@ +getName())]; + } + + // Receiver is still not a callable which means it's not a valid receiver. + if (is_callable($receiver) == false) { + return null; + } + + return new Receiver\CallableReceiver($receiver); + } +} diff --git a/src/Router/SimpleRouter.php b/src/Router/SimpleRouter.php deleted file mode 100644 index bfd0af74..00000000 --- a/src/Router/SimpleRouter.php +++ /dev/null @@ -1,116 +0,0 @@ - $receiver) { - $this->add($name, $receiver); - } - } - - /** - * @param string $name - * @param mixed $receiver - */ - private function add($name, $receiver) - { - if (!$this->accepts($receiver)) { - throw new \InvalidArgumentException(sprintf('Given "%s" is not supported.', $receiver)); - } - - $this->receivers[$name] = $receiver; - } - - /** - * {@inheritdoc} - */ - public function map(Envelope $envelope) - { - $receiver = $this->get($this->getName($envelope)); - $receiver = $this->resolveReceiver($receiver, $envelope); - - if (null === $receiver) { - throw new ReceiverNotFoundException(sprintf('No receiver found with name "%s".', $envelope->getName())); - } - - return $receiver; - } - - /** - * @param mixed $receiver - * - * @return bool - */ - protected function accepts($receiver) - { - return is_callable($receiver) || is_object($receiver) || class_exists($receiver); - } - - /** - * @param string $name - * - * @return mixed - */ - protected function get($name) - { - return isset($this->receivers[$name]) ? $this->receivers[$name] : null; - } - - /** - * Returns the (message) name to look for in the receiver map. - * - * @param Envelope $envelope - * - * @return string - */ - protected function getName(Envelope $envelope) - { - return $envelope->getName(); - } - - /** - * Resolves a receiver or returns null. - * - * @param mixed $receiver - * @param Envelope $envelope - * - * @return Receiver|null - */ - private function resolveReceiver($receiver, Envelope $envelope) - { - if (null === $receiver) { - return null; - } - - if ($receiver instanceof Receiver) { - return $receiver; - } - - if (is_callable($receiver) == false) { - $receiver = [$receiver, lcfirst($envelope->getName())]; - } - - // Receiver is still not a callable which means it's not a valid receiver. - if (is_callable($receiver) == false) { - return null; - } - - return new Receiver\CallableReceiver($receiver); - } -} diff --git a/tests/Router/SimpleRouterTest.php b/tests/Router/SimpleRouterTest.php deleted file mode 100644 index f1a87765..00000000 --- a/tests/Router/SimpleRouterTest.php +++ /dev/null @@ -1,72 +0,0 @@ -router = new SimpleRouter(); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testThrowsExceptionWhenReceiverIsNotSupported() - { - $this->router = new SimpleRouter([ - 'SendNewsletter' => 1, - ]); - } - - /** - * @expectedException \Bernard\Exception\ReceiverNotFoundException - */ - public function testThrowsExceptionWhenNothingMatches() - { - $envelope = new Envelope(new PlainMessage('SendNewsletter')); - - $this->router->map($envelope); - } - - public function testReceiversAreAddedThroughConstructor() - { - $receiver = $this->prophesize(Receiver::class)->reveal(); - $envelope = new Envelope(new PlainMessage('SendNewsletter')); - - $router = new SimpleRouter([ - 'SendNewsletter' => $receiver, - ]); - - $this->assertSame($receiver, $router->map($envelope)); - } - - /** - * @dataProvider provideCallable - */ - public function testItReturnsCallable($given, $expected) - { - $this->router = new SimpleRouter([ - 'SendNewsletter' => $given, - ]); - - $envelope = new Envelope(new PlainMessage('SendNewsletter')); - - $this->assertInstanceOf(Receiver::class, $this->router->map($envelope)); - } - - public function provideCallable() - { - $callable = function () {}; - - return [ - ['var_dump', 'var_dump'], - [$callable, $callable], - ]; - } -} From 2060886046046bd04141e4e673527e60218eda29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 11:47:51 +0100 Subject: [PATCH 047/108] Rename Router::map to Router::route --- spec/Router/ClassNameRouterSpec.php | 6 +++--- spec/Router/ReceiverMapRouterSpec.php | 4 ++-- src/Consumer.php | 2 +- src/Router.php | 2 +- src/Router/ReceiverMapRouter.php | 2 +- tests/ConsumerTest.php | 24 ++++++++++++------------ 6 files changed, 20 insertions(+), 20 deletions(-) diff --git a/spec/Router/ClassNameRouterSpec.php b/spec/Router/ClassNameRouterSpec.php index 0c565849..e4e65174 100644 --- a/spec/Router/ClassNameRouterSpec.php +++ b/spec/Router/ClassNameRouterSpec.php @@ -36,7 +36,7 @@ function it_routes_an_envelope_to_a_receiver(Message $message, Router\ReceiverRe $receiverResolver ); - $this->map($envelope)->shouldReturn($receiver); + $this->route($envelope)->shouldReturn($receiver); } function it_routes_an_envelope_to_a_receiver_based_on_message_parent(Message $message, Router\ReceiverResolver $receiverResolver, Receiver $receiver) @@ -53,7 +53,7 @@ function it_routes_an_envelope_to_a_receiver_based_on_message_parent(Message $me $receiverResolver ); - $this->map($envelope)->shouldReturn($receiver); + $this->route($envelope)->shouldReturn($receiver); } function it_throws_an_exception_when_a_receiver_is_not_accepted(Router\ReceiverResolver $receiverResolver) @@ -85,6 +85,6 @@ function it_throws_an_exception_when_an_envelop_cannot_be_routed_to_a_receiver(M $receiverResolver ); - $this->shouldThrow(ReceiverNotFoundException::class)->duringMap($envelope); + $this->shouldThrow(ReceiverNotFoundException::class)->duringRoute($envelope); } } diff --git a/spec/Router/ReceiverMapRouterSpec.php b/spec/Router/ReceiverMapRouterSpec.php index c0fdf63d..af710441 100644 --- a/spec/Router/ReceiverMapRouterSpec.php +++ b/spec/Router/ReceiverMapRouterSpec.php @@ -37,7 +37,7 @@ function it_routes_an_envelope_to_a_receiver(Message $message, Router\ReceiverRe $receiverResolver ); - $this->map($envelope)->shouldReturn($receiver); + $this->route($envelope)->shouldReturn($receiver); } function it_throws_an_exception_when_a_receiver_is_not_accepted(Router\ReceiverResolver $receiverResolver) @@ -69,6 +69,6 @@ function it_throws_an_exception_when_an_envelop_cannot_be_routed_to_a_receiver(M $receiverResolver ); - $this->shouldThrow(ReceiverNotFoundException::class)->duringMap($envelope); + $this->shouldThrow(ReceiverNotFoundException::class)->duringRoute($envelope); } } diff --git a/src/Consumer.php b/src/Consumer.php index 15daa5b2..2fefc087 100644 --- a/src/Consumer.php +++ b/src/Consumer.php @@ -127,7 +127,7 @@ public function invoke(Envelope $envelope, Queue $queue) try { $this->dispatcher->dispatch(BernardEvents::INVOKE, new EnvelopeEvent($envelope, $queue)); - $receiver = $this->router->map($envelope); + $receiver = $this->router->route($envelope); $receiver->receive($envelope->getMessage()); // We successfully processed the message. diff --git a/src/Router.php b/src/Router.php index 16d60ba8..6c924988 100644 --- a/src/Router.php +++ b/src/Router.php @@ -18,5 +18,5 @@ interface Router * * @throws ReceiverNotFoundException */ - public function map(Envelope $envelope); + public function route(Envelope $envelope); } diff --git a/src/Router/ReceiverMapRouter.php b/src/Router/ReceiverMapRouter.php index 4e2a38c3..d3229464 100644 --- a/src/Router/ReceiverMapRouter.php +++ b/src/Router/ReceiverMapRouter.php @@ -48,7 +48,7 @@ private function add($name, $receiver) /** * {@inheritdoc} */ - public function map(Envelope $envelope) + public function route(Envelope $envelope) { $receiver = $this->get($this->getName($envelope)); $receiver = $this->receiverResolver->resolve($receiver, $envelope); diff --git a/tests/ConsumerTest.php b/tests/ConsumerTest.php index 8d0c4dd7..da0ee78e 100644 --- a/tests/ConsumerTest.php +++ b/tests/ConsumerTest.php @@ -51,7 +51,7 @@ public function testEmitsConsumeEvent() /** @var Receiver|ObjectProphecy $receiver */ $receiver = $this->prophesize(Receiver::class); $receiver->receive($message)->shouldBeCalled(); - $this->router->map($envelope)->willReturn($receiver); + $this->router->route($envelope)->willReturn($receiver); $queue->expects($this->once()) ->method('dequeue') @@ -79,7 +79,7 @@ public function testEmitsExceptionEvent() /** @var Receiver|ObjectProphecy $receiver */ $receiver = $this->prophesize(Receiver::class); $receiver->receive($message)->willThrow($exception); - $this->router->map($envelope)->willReturn($receiver); + $this->router->route($envelope)->willReturn($receiver); $this->dispatcher->expects($this->at(1))->method('dispatch') ->with('bernard.reject', new RejectEnvelopeEvent($envelope, $queue, $exception)); @@ -105,7 +105,7 @@ public function testPauseResume() /** @var Receiver|ObjectProphecy $receiver */ $receiver = $this->prophesize(Receiver::class); $receiver->receive($message)->shouldBeCalled(); - $this->router->map($envelope)->willReturn($receiver); + $this->router->route($envelope)->willReturn($receiver); $this->consumer->pause(); @@ -138,7 +138,7 @@ public function testEnvelopeIsAcknowledged() /** @var Receiver|ObjectProphecy $receiver */ $receiver = $this->prophesize(Receiver::class); $receiver->receive($message)->shouldBeCalled(); - $this->router->map($envelope)->willReturn($receiver); + $this->router->route($envelope)->willReturn($receiver); $queue = $this->createMock('Bernard\Queue'); $queue->expects($this->once())->method('dequeue')->will($this->returnValue($envelope)); @@ -163,9 +163,9 @@ public function testMaxMessages() $receiver->receive($message1)->shouldBeCalled(); $receiver->receive($message2)->shouldBeCalled(); $receiver->receive($message3)->shouldBeCalled(); - $this->router->map($envelope1)->willReturn($receiver); - $this->router->map($envelope2)->willReturn($receiver); - $this->router->map($envelope3)->willReturn($receiver); + $this->router->route($envelope1)->willReturn($receiver); + $this->router->route($envelope2)->willReturn($receiver); + $this->router->route($envelope3)->willReturn($receiver); $this->assertFalse($this->consumer->tick($queue, ['max-messages' => 1])); $this->assertTrue($this->consumer->tick($queue)); @@ -185,8 +185,8 @@ public function testStopAfterLastMessage() $receiver = $this->prophesize(Receiver::class); $receiver->receive($message1)->shouldBeCalled(); $receiver->receive($message2)->shouldBeCalled(); - $this->router->map($envelope1)->willReturn($receiver); - $this->router->map($envelope2)->willReturn($receiver); + $this->router->route($envelope1)->willReturn($receiver); + $this->router->route($envelope2)->willReturn($receiver); $this->assertTrue($this->consumer->tick($queue, ['stop-when-empty' => true])); $this->assertTrue($this->consumer->tick($queue, ['stop-when-empty' => true])); @@ -203,7 +203,7 @@ public function testStopOnError() $queue = new InMemoryQueue('send-newsletter'); $queue->enqueue($envelope); - $this->router->map($envelope)->willThrow(ReceiverNotFoundException::class); + $this->router->route($envelope)->willThrow(ReceiverNotFoundException::class); $this->consumer->tick($queue, ['stop-on-error' => true]); @@ -223,7 +223,7 @@ public function testEnvelopeWillBeInvoked() /** @var Receiver|ObjectProphecy $receiver */ $receiver = $this->prophesize(Receiver::class); $receiver->receive($message)->shouldBeCalled(); - $this->router->map($envelope)->willReturn($receiver); + $this->router->route($envelope)->willReturn($receiver); $this->consumer->tick($queue); } @@ -242,7 +242,7 @@ public function testWillRejectDispatchOnThrowableError() /** @var Receiver|ObjectProphecy $receiver */ $receiver = $this->prophesize(Receiver::class); $receiver->receive($message)->willThrow(\TypeError::class); - $this->router->map($envelope)->willReturn($receiver); + $this->router->route($envelope)->willReturn($receiver); $this->dispatcher->expects(self::at(0))->method('dispatch')->with('bernard.ping'); $this->dispatcher->expects(self::at(1))->method('dispatch')->with('bernard.invoke'); From f4c03f73b85ff1c12a05394d1a2edb382f327c1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Sun, 18 Feb 2018 11:52:13 +0100 Subject: [PATCH 048/108] Fix minimum dev requirement --- composer.json | 1 + 1 file changed, 1 insertion(+) diff --git a/composer.json b/composer.json index 9fdcaf7a..11ef686e 100644 --- a/composer.json +++ b/composer.json @@ -23,6 +23,7 @@ "php-amqplib/php-amqplib": "~2.5", "phpspec/phpspec": "^3.0 || ^4.0", "leanphp/phpspec-code-coverage": "^3.0 || ^4.0", + "doctrine/instantiator": "^1.0.5", "phpunit/phpunit": "^5.5 || ^6.0 || ^7.0", "iron-io/iron_mq": "~4.0", "queue-interop/queue-interop": "^0.6", From 3c1b1306211bd6130f7c7117ecbae88ff02831e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Mon, 19 Feb 2018 00:04:40 +0100 Subject: [PATCH 049/108] Upgrade symfony --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 50eb6d8b..962d2cf3 100644 --- a/composer.json +++ b/composer.json @@ -9,14 +9,14 @@ "require": { "php": "^5.6 || ^7.0", "bernard/normalt": "~1.0", - "symfony/event-dispatcher": "^2.7|^3.0|^4.0", + "symfony/event-dispatcher": "^3.0 || ^4.0", "beberlei/assert": "~2.1" }, "require-dev" : { "psr/log": "^1.0", "psr/container": "^1.0", "predis/predis": "~0.8", - "symfony/console": "^2.7|^3.0|^4.0", + "symfony/console": "^3.0 || ^4.0", "doctrine/dbal": "~2.3", "aws/aws-sdk-php": "~2.4|~3.0", "pda/pheanstalk": "~3.0", From c68e0437ced66c0477394e36a9a68edac1c09d31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Mon, 19 Feb 2018 00:08:18 +0100 Subject: [PATCH 050/108] Upgrade predis --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 962d2cf3..539ae8d4 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,7 @@ "require-dev" : { "psr/log": "^1.0", "psr/container": "^1.0", - "predis/predis": "~0.8", + "predis/predis": "^1.0", "symfony/console": "^3.0 || ^4.0", "doctrine/dbal": "~2.3", "aws/aws-sdk-php": "~2.4|~3.0", From 344c00ee1af7e8fd6a6fc4ace99bdc8fb15af3bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Mon, 19 Feb 2018 00:10:27 +0100 Subject: [PATCH 051/108] Upgrade DBAL --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 539ae8d4..72f7a22d 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ "psr/container": "^1.0", "predis/predis": "^1.0", "symfony/console": "^3.0 || ^4.0", - "doctrine/dbal": "~2.3", + "doctrine/dbal": "^2.5", "aws/aws-sdk-php": "~2.4|~3.0", "pda/pheanstalk": "~3.0", "php-amqplib/php-amqplib": "~2.5", From 1611dbd3dee79c2f5df4b7d42023f3c2d87d5d26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Mon, 19 Feb 2018 00:10:53 +0100 Subject: [PATCH 052/108] Upgrade AWS SDK --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 72f7a22d..a1c5c5c2 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,7 @@ "predis/predis": "^1.0", "symfony/console": "^3.0 || ^4.0", "doctrine/dbal": "^2.5", - "aws/aws-sdk-php": "~2.4|~3.0", + "aws/aws-sdk-php": "^3.0", "pda/pheanstalk": "~3.0", "php-amqplib/php-amqplib": "~2.5", "phpspec/phpspec": "^3.0 || ^4.0", From e868b4a7cf2e149757564176f703deb90c25734c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Mon, 19 Feb 2018 00:12:21 +0100 Subject: [PATCH 053/108] Upgrade version constraints --- composer.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index a1c5c5c2..db5c048d 100644 --- a/composer.json +++ b/composer.json @@ -8,9 +8,9 @@ "require": { "php": "^5.6 || ^7.0", - "bernard/normalt": "~1.0", + "bernard/normalt": "^1.0", "symfony/event-dispatcher": "^3.0 || ^4.0", - "beberlei/assert": "~2.1" + "beberlei/assert": "^2.1" }, "require-dev" : { "psr/log": "^1.0", @@ -19,13 +19,13 @@ "symfony/console": "^3.0 || ^4.0", "doctrine/dbal": "^2.5", "aws/aws-sdk-php": "^3.0", - "pda/pheanstalk": "~3.0", - "php-amqplib/php-amqplib": "~2.5", + "pda/pheanstalk": "^3.0", + "php-amqplib/php-amqplib": "^2.5", "phpspec/phpspec": "^3.0 || ^4.0", "leanphp/phpspec-code-coverage": "^3.0 || ^4.0", "doctrine/instantiator": "^1.0.5", "phpunit/phpunit": "^5.5 || ^6.0 || ^7.0", - "iron-io/iron_mq": "~4.0", + "iron-io/iron_mq": "^4.0", "queue-interop/queue-interop": "^0.6", "queue-interop/amqp-interop": "^0.6" }, From 0d100e7da1d3888e2b1995e01a3b18a6798fd220 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Mon, 19 Feb 2018 01:07:35 +0100 Subject: [PATCH 054/108] Update package --- .gitattributes | 15 ++++++----- .gitignore | 6 ++--- .php_cs.dist | 2 +- .travis.yml | 26 ++++++++++--------- composer.json | 14 ++++++---- spec/.php_cs.dist | 15 +++++++++++ spec/Receiver/CallableReceiverSpec.php | 4 +-- .../Router/ContainerNotFoundExceptionStub.php | 4 ++- spec/Router/ContainerReceiverResolverSpec.php | 2 +- spec/Router/ReceiverStub.php | 2 -- spec/Router/SimpleReceiverResolverSpec.php | 4 +-- 11 files changed, 59 insertions(+), 35 deletions(-) create mode 100644 spec/.php_cs.dist diff --git a/.gitattributes b/.gitattributes index 2b7564bf..0465b39f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,11 +1,14 @@ -/doc/ export-ignore -/spec/ export-ignore -/tests/ export-ignore -/.editorconfig export-ignore -/.gitattributes export-ignore -/.gitignore export-ignore +.editorconfig export-ignore +.gitattributes export-ignore +.gitignore export-ignore +/.flintci.yml export-ignore +/.github/ export-ignore /.php_cs.dist export-ignore +/.scrutinizer.yml export-ignore /.travis.yml export-ignore +/doc/ export-ignore /phpspec.ci.yml export-ignore /phpspec.yml.dist export-ignore /phpunit.xml.dist export-ignore +/spec/ export-ignore +/tests/ export-ignore diff --git a/.gitignore b/.gitignore index 019557db..46f37ce3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,8 @@ -/build/ +.php_cs +.php_cs.cache /_build/ +/build/ /composer.lock /phpspec.yml /phpunit.xml -/.php_cs -/.php_cs.cache /vendor/ diff --git a/.php_cs.dist b/.php_cs.dist index 44307173..dac69adf 100644 --- a/.php_cs.dist +++ b/.php_cs.dist @@ -12,4 +12,4 @@ return PhpCsFixer\Config::create() 'yoda_style' => false, ]) ->setFinder($finder) - ; +; diff --git a/.travis.yml b/.travis.yml index 2ae645b5..9337412f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,17 +1,22 @@ language: php -dist: trusty - sudo: false cache: directories: - $HOME/.composer/cache/files + php: - - 5.6 - - 7.0 - - 7.1 - - 7.2 + - 5.6 + - 7.0 + - 7.1 + - 7.2 + - nightly + +services: + - mongodb + - mysql + - postgresql env: global: @@ -19,14 +24,11 @@ env: matrix: fast_finish: true + allow_failures: + - php: nightly include: - php: 5.6 - env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest" COVERAGE=true TEST_COMMAND="composer test-ci" - -services: - - mongodb - - mysql - - postgresql + env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest" COVERAGE=true TEST_COMMAND="composer test-coverage" before_install: - if [[ $COVERAGE != true ]]; then phpenv config-rm xdebug.ini || true; fi diff --git a/composer.json b/composer.json index db5c048d..497f102d 100644 --- a/composer.json +++ b/composer.json @@ -1,11 +1,10 @@ { "name": "bernard/bernard", "description": "Message queue abstraction layer", + "license": "MIT", "keywords": ["message queue", "message", "queue", "bernard"], "homepage": "https://github.com/bernardphp/bernard", "type": "library", - "license": "MIT", - "require": { "php": "^5.6 || ^7.0", "bernard/normalt": "^1.0", @@ -40,7 +39,6 @@ "queue-interop/queue-interop": "Allow sending messages using queue interop compatible transports", "queue-interop/amqp-interop": "Allow sending messages using amqp interop compatible transports" }, - "autoload" : { "psr-4" : { "Bernard\\" : "src/" } }, @@ -50,12 +48,16 @@ "spec\\Bernard\\" : "spec/" } }, + "config": { + "sort-packages": true + }, "scripts": { + "clean": "rm -rf build/ vendor/", "test": [ "vendor/bin/phpspec run", "vendor/bin/phpunit -v" ], - "test-ci": [ + "test-coverage": [ "vendor/bin/phpspec run -c phpspec.ci.yml", "vendor/bin/phpunit -v --coverage-text --coverage-clover=build/unit_coverage.xml" ], @@ -65,5 +67,7 @@ "branch-alias" : { "dev-master" : "1.0.x-dev" } - } + }, + "prefer-stable": true, + "minimum-stability": "dev" } diff --git a/spec/.php_cs.dist b/spec/.php_cs.dist new file mode 100644 index 00000000..599607ef --- /dev/null +++ b/spec/.php_cs.dist @@ -0,0 +1,15 @@ +in(__DIR__) +; + +return PhpCsFixer\Config::create() + ->setRules([ + '@Symfony' => true, + 'array_syntax' => ['syntax' => 'short'], + 'yoda_style' => false, + 'visibility_required' => [], + ]) + ->setFinder($finder) +; diff --git a/spec/Receiver/CallableReceiverSpec.php b/spec/Receiver/CallableReceiverSpec.php index d458513a..88744c3a 100644 --- a/spec/Receiver/CallableReceiverSpec.php +++ b/spec/Receiver/CallableReceiverSpec.php @@ -11,7 +11,7 @@ class CallableReceiverSpec extends ObjectBehavior { function let() { - $this->beConstructedWith(function() {}); + $this->beConstructedWith(function () {}); } function it_is_initializable() @@ -26,7 +26,7 @@ function it_is_a_receiver() function it_receives_a_message(Message $message) { - $this->beConstructedWith(function(Message $message) { + $this->beConstructedWith(function (Message $message) { $message->getName(); }); diff --git a/spec/Router/ContainerNotFoundExceptionStub.php b/spec/Router/ContainerNotFoundExceptionStub.php index af023fa8..9ac7a3ef 100644 --- a/spec/Router/ContainerNotFoundExceptionStub.php +++ b/spec/Router/ContainerNotFoundExceptionStub.php @@ -4,4 +4,6 @@ use Psr\Container\NotFoundExceptionInterface; -class ContainerNotFoundExceptionStub extends \Exception implements NotFoundExceptionInterface {} +class ContainerNotFoundExceptionStub extends \Exception implements NotFoundExceptionInterface +{ +} diff --git a/spec/Router/ContainerReceiverResolverSpec.php b/spec/Router/ContainerReceiverResolverSpec.php index 7741e674..fb123606 100644 --- a/spec/Router/ContainerReceiverResolverSpec.php +++ b/spec/Router/ContainerReceiverResolverSpec.php @@ -50,7 +50,7 @@ function it_returns_the_receiver_when_it_is_already_a_receiver(Message $message, function it_returns_a_callable_receiver_when_the_receiver_is_callable(Message $message, ContainerInterface $container) { - $container->get('my.service')->willReturn(function(Message $message) {}); + $container->get('my.service')->willReturn(function (Message $message) {}); $this->resolve('my.service', new Envelope($message->getWrappedObject()))->shouldHaveType(Receiver\CallableReceiver::class); } diff --git a/spec/Router/ReceiverStub.php b/spec/Router/ReceiverStub.php index 27205d01..78094ad4 100644 --- a/spec/Router/ReceiverStub.php +++ b/spec/Router/ReceiverStub.php @@ -6,11 +6,9 @@ class ReceiverStub { public static function staticMessageName($message) { - } public static function messageName($message) { - } } diff --git a/spec/Router/SimpleReceiverResolverSpec.php b/spec/Router/SimpleReceiverResolverSpec.php index 2a6401d0..1d0d9325 100644 --- a/spec/Router/SimpleReceiverResolverSpec.php +++ b/spec/Router/SimpleReceiverResolverSpec.php @@ -23,7 +23,7 @@ function it_is_a_receiver_resolver() function it_accepts_a_callable_receiver() { - $callable = function(Message $message) {}; + $callable = function (Message $message) {}; $this->accepts($callable)->shouldReturn(true); } @@ -50,7 +50,7 @@ function it_returns_the_receiver_when_it_is_already_a_receiver(Message $message, function it_returns_a_callable_receiver_when_the_receiver_is_callable(Message $message) { - $callable = function(Message $message) {}; + $callable = function (Message $message) {}; $this->resolve($callable, new Envelope($message->getWrappedObject()))->shouldHaveType(Receiver\CallableReceiver::class); } From 82ef887e7ae277fd5fec2c514f3b039cddddd8ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Mon, 19 Feb 2018 01:25:10 +0100 Subject: [PATCH 055/108] Sort packages --- composer.json | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/composer.json b/composer.json index 497f102d..23e83e5b 100644 --- a/composer.json +++ b/composer.json @@ -7,26 +7,26 @@ "type": "library", "require": { "php": "^5.6 || ^7.0", + "beberlei/assert": "^2.1", "bernard/normalt": "^1.0", - "symfony/event-dispatcher": "^3.0 || ^4.0", - "beberlei/assert": "^2.1" + "symfony/event-dispatcher": "^3.0 || ^4.0" }, "require-dev" : { - "psr/log": "^1.0", - "psr/container": "^1.0", - "predis/predis": "^1.0", - "symfony/console": "^3.0 || ^4.0", - "doctrine/dbal": "^2.5", "aws/aws-sdk-php": "^3.0", + "doctrine/dbal": "^2.5", + "doctrine/instantiator": "^1.0.5", + "iron-io/iron_mq": "^4.0", + "leanphp/phpspec-code-coverage": "^3.0 || ^4.0", "pda/pheanstalk": "^3.0", "php-amqplib/php-amqplib": "^2.5", "phpspec/phpspec": "^3.0 || ^4.0", - "leanphp/phpspec-code-coverage": "^3.0 || ^4.0", - "doctrine/instantiator": "^1.0.5", - "phpunit/phpunit": "^5.5 || ^6.0 || ^7.0", - "iron-io/iron_mq": "^4.0", + "phpunit/phpunit": "^5.7 || ^6.0 || ^7.0", + "predis/predis": "^1.0", + "psr/container": "^1.0", + "psr/log": "^1.0", + "queue-interop/amqp-interop": "^0.6", "queue-interop/queue-interop": "^0.6", - "queue-interop/amqp-interop": "^0.6" + "symfony/console": "^3.0 || ^4.0" }, "suggest": { "php-amqplib/php-amqplib": "Allow sending messages to an AMQP server using php-amqplib", From 1d7a5e7dc07c81750f454506ed6e22c55def6deb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Mon, 19 Feb 2018 01:28:09 +0100 Subject: [PATCH 056/108] Update phpunit configuration --- phpunit.xml.dist | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 6009990d..87ecdfd4 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,13 +1,9 @@ - + @@ -16,7 +12,7 @@ - + ./src From 7181d149e846880e9b8623159a68f3eb5d3b7b50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Mon, 19 Feb 2018 01:28:46 +0100 Subject: [PATCH 057/108] Update phpspec config --- phpspec.ci.yml | 2 +- phpspec.yml.dist | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/phpspec.ci.yml b/phpspec.ci.yml index b5263b2a..b53b4223 100644 --- a/phpspec.ci.yml +++ b/phpspec.ci.yml @@ -1,5 +1,5 @@ suites: - bernard_suite: + main: namespace: Bernard psr4_prefix: Bernard formatter.name: pretty diff --git a/phpspec.yml.dist b/phpspec.yml.dist index a82bebf6..d4b15f40 100644 --- a/phpspec.yml.dist +++ b/phpspec.yml.dist @@ -1,5 +1,5 @@ suites: - bernard_suite: + main: namespace: Bernard psr4_prefix: Bernard formatter.name: pretty From d26bf21d341f8a6dc13c5b132b6106a690358057 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rk=20S=C3=A1gi-Kaz=C3=A1r?= Date: Mon, 19 Feb 2018 01:43:05 +0100 Subject: [PATCH 058/108] Update PHPUnit config --- phpunit.xml.dist | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 87ecdfd4..6345d7f3 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,9 +1,9 @@ - + From 5679a44530e0c6a0e25a4864757f58579dbcf018 Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Thu, 12 Apr 2018 23:34:57 -0300 Subject: [PATCH 059/108] Use dedicated PHPUnit assertions --- tests/Driver/Doctrine/AbstractDriverTest.php | 2 +- tests/Driver/FlatFile/DriverTest.php | 6 +++--- tests/Message/PlainMessageTest.php | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/Driver/Doctrine/AbstractDriverTest.php b/tests/Driver/Doctrine/AbstractDriverTest.php index 52099e97..f02e9994 100644 --- a/tests/Driver/Doctrine/AbstractDriverTest.php +++ b/tests/Driver/Doctrine/AbstractDriverTest.php @@ -55,7 +55,7 @@ public function testPopMessageWithInterval() $this->driver->popMessage('non-existent-queue', 0.001); - $this->assertTrue((microtime(true) - $microtime) >= 0.001); + $this->assertGreaterThanOrEqual(0.001, microtime(true) - $microtime); } public function testCreateAndRemoveQueue() diff --git a/tests/Driver/FlatFile/DriverTest.php b/tests/Driver/FlatFile/DriverTest.php index cc9094ed..7944d2ed 100644 --- a/tests/Driver/FlatFile/DriverTest.php +++ b/tests/Driver/FlatFile/DriverTest.php @@ -39,7 +39,7 @@ public function testCreate() $this->driver->createQueue('send-newsletter'); $this->driver->createQueue('send-newsletter'); - $this->assertTrue(is_dir($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter')); + $this->assertDirectoryExists($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'); } public function testRemove() @@ -49,7 +49,7 @@ public function testRemove() $this->driver->removeQueue('send-newsletter'); - $this->assertFalse(is_dir($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter')); + $this->assertDirectoryNotExists($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'); } public function testRemoveQueueWithPoppedMessage() @@ -60,7 +60,7 @@ public function testRemoveQueueWithPoppedMessage() $this->driver->removeQueue('send-newsletter'); - $this->assertFalse(is_dir($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter')); + $this->assertDirectoryNotExists($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'); } public function testPushMessage() diff --git a/tests/Message/PlainMessageTest.php b/tests/Message/PlainMessageTest.php index fa6e164f..7678cc12 100644 --- a/tests/Message/PlainMessageTest.php +++ b/tests/Message/PlainMessageTest.php @@ -17,7 +17,7 @@ public function it_has_arguments() 'key3' => null, ]); - $this->assertTrue(isset($message['key1'])); + $this->assertArrayHasKey('key1', $message); $this->assertEquals(1, $message['key1']); $this->assertEquals([1, 2, 3, 4], $message['key2']); From 5093a5ed607263ca8c26afcf9291402babc54764 Mon Sep 17 00:00:00 2001 From: karser Date: Mon, 28 May 2018 15:06:07 +0300 Subject: [PATCH 060/108] throw InsufficientPermissionsException if FlatFile driver https://github.com/bernardphp/bernard/issues/382 --- src/Driver/FlatFile/Driver.php | 17 +++++++++++++++++ .../InsufficientPermissionsException.php | 6 ++++++ 2 files changed, 23 insertions(+) create mode 100644 src/Exception/InsufficientPermissionsException.php diff --git a/src/Driver/FlatFile/Driver.php b/src/Driver/FlatFile/Driver.php index 2bdd44d8..2d0c1f57 100644 --- a/src/Driver/FlatFile/Driver.php +++ b/src/Driver/FlatFile/Driver.php @@ -2,6 +2,8 @@ namespace Bernard\Driver\FlatFile; +use Bernard\Exception\InsufficientPermissionsException; + /** * Flat file driver to provide a simple job queue without any * database. @@ -105,6 +107,7 @@ public function popMessage($queueName, $duration = 5) if (@rename($queueDir.DIRECTORY_SEPARATOR.$id, $queueDir.DIRECTORY_SEPARATOR.$id.'.proceed')) { return [file_get_contents($queueDir.DIRECTORY_SEPARATOR.$id.'.proceed'), $id]; } + return $this->process($queueDir, $id); } usleep(1000); @@ -113,6 +116,20 @@ public function popMessage($queueName, $duration = 5) return [null, null]; } + /** + * @param string $queueDir + * @param string $id + * @return array + */ + private function process($queueDir, $id) { + $name = $queueDir.DIRECTORY_SEPARATOR.$id; + $newName = $name.'.proceed'; + if (!@rename($name, $newName)) { + throw new InsufficientPermissionsException("Unable to process file: '{$name}'"); + } + return [file_get_contents($newName), $id]; + } + /** * {@inheritdoc} */ diff --git a/src/Exception/InsufficientPermissionsException.php b/src/Exception/InsufficientPermissionsException.php new file mode 100644 index 00000000..3026b165 --- /dev/null +++ b/src/Exception/InsufficientPermissionsException.php @@ -0,0 +1,6 @@ + Date: Mon, 28 May 2018 15:14:56 +0300 Subject: [PATCH 061/108] style guide compliance https://github.com/bernardphp/bernard/issues/382 --- src/Driver/FlatFile/Driver.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Driver/FlatFile/Driver.php b/src/Driver/FlatFile/Driver.php index 2d0c1f57..939fac2d 100644 --- a/src/Driver/FlatFile/Driver.php +++ b/src/Driver/FlatFile/Driver.php @@ -107,6 +107,7 @@ public function popMessage($queueName, $duration = 5) if (@rename($queueDir.DIRECTORY_SEPARATOR.$id, $queueDir.DIRECTORY_SEPARATOR.$id.'.proceed')) { return [file_get_contents($queueDir.DIRECTORY_SEPARATOR.$id.'.proceed'), $id]; } + return $this->process($queueDir, $id); } @@ -124,6 +125,7 @@ public function popMessage($queueName, $duration = 5) private function process($queueDir, $id) { $name = $queueDir.DIRECTORY_SEPARATOR.$id; $newName = $name.'.proceed'; + if (!@rename($name, $newName)) { throw new InsufficientPermissionsException("Unable to process file: '{$name}'"); } From 7b339ad2f6b9a58721bf0efa653a0c35bc42cbc5 Mon Sep 17 00:00:00 2001 From: karser Date: Tue, 29 May 2018 15:20:53 +0300 Subject: [PATCH 062/108] more style guide compliance https://github.com/bernardphp/bernard/issues/382 --- src/Driver/FlatFile/Driver.php | 6 +++--- src/Driver/FlatFile/InsufficientPermissionsException.php | 9 +++++++++ src/Exception/InsufficientPermissionsException.php | 6 ------ 3 files changed, 12 insertions(+), 9 deletions(-) create mode 100644 src/Driver/FlatFile/InsufficientPermissionsException.php delete mode 100644 src/Exception/InsufficientPermissionsException.php diff --git a/src/Driver/FlatFile/Driver.php b/src/Driver/FlatFile/Driver.php index 939fac2d..10e974ac 100644 --- a/src/Driver/FlatFile/Driver.php +++ b/src/Driver/FlatFile/Driver.php @@ -2,8 +2,6 @@ namespace Bernard\Driver\FlatFile; -use Bernard\Exception\InsufficientPermissionsException; - /** * Flat file driver to provide a simple job queue without any * database. @@ -120,6 +118,7 @@ public function popMessage($queueName, $duration = 5) /** * @param string $queueDir * @param string $id + * * @return array */ private function process($queueDir, $id) { @@ -127,8 +126,9 @@ private function process($queueDir, $id) { $newName = $name.'.proceed'; if (!@rename($name, $newName)) { - throw new InsufficientPermissionsException("Unable to process file: '{$name}'"); + throw new InsufficientPermissionsException('Unable to process file: '.$name); } + return [file_get_contents($newName), $id]; } diff --git a/src/Driver/FlatFile/InsufficientPermissionsException.php b/src/Driver/FlatFile/InsufficientPermissionsException.php new file mode 100644 index 00000000..20c5d19c --- /dev/null +++ b/src/Driver/FlatFile/InsufficientPermissionsException.php @@ -0,0 +1,9 @@ + Date: Thu, 31 May 2018 00:27:18 +0300 Subject: [PATCH 063/108] the more meaningful function name https://github.com/bernardphp/bernard/issues/382 --- src/Driver/FlatFile/Driver.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Driver/FlatFile/Driver.php b/src/Driver/FlatFile/Driver.php index 10e974ac..c1df5cfc 100644 --- a/src/Driver/FlatFile/Driver.php +++ b/src/Driver/FlatFile/Driver.php @@ -106,7 +106,7 @@ public function popMessage($queueName, $duration = 5) return [file_get_contents($queueDir.DIRECTORY_SEPARATOR.$id.'.proceed'), $id]; } - return $this->process($queueDir, $id); + return $this->processFileOrFail($queueDir, $id); } usleep(1000); @@ -121,7 +121,7 @@ public function popMessage($queueName, $duration = 5) * * @return array */ - private function process($queueDir, $id) { + private function processFileOrFail($queueDir, $id) { $name = $queueDir.DIRECTORY_SEPARATOR.$id; $newName = $name.'.proceed'; From 07228665bad37d9df883a9f95da8a2d86dbc1aea Mon Sep 17 00:00:00 2001 From: Yumin Gui Date: Sat, 2 Jun 2018 13:23:56 -0700 Subject: [PATCH 064/108] A typo is fixed. completly -> completely --- doc/queues.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/queues.rst b/doc/queues.rst index f3df7269..dde1b2ff 100644 --- a/doc/queues.rst +++ b/doc/queues.rst @@ -16,7 +16,7 @@ With the roundrobin queue you can produce messages to multiple queues In Memory Queue --------------- -Bernard comes with an implementation for ``SplQueue`` which is completly in memory. +Bernard comes with an implementation for ``SplQueue`` which is completely in memory. It is useful for development and/or testing, when you don't necessarily want actions to be performed. From 3ff88921bea87186d1baffc93708dd7aee4e963e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Uwe=20J=C3=A4ger?= Date: Sun, 24 Jun 2018 13:41:28 +0200 Subject: [PATCH 065/108] Fix doctrine peek master (#380) Return only visible (not popped) messages when peeking the queue --- src/Driver/Doctrine/Driver.php | 6 +++--- tests/Driver/Doctrine/AbstractDriverTest.php | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/Driver/Doctrine/Driver.php b/src/Driver/Doctrine/Driver.php index dd1ec374..415e91b9 100644 --- a/src/Driver/Doctrine/Driver.php +++ b/src/Driver/Doctrine/Driver.php @@ -112,10 +112,10 @@ public function acknowledgeMessage($queueName, $receipt) */ public function peekQueue($queueName, $index = 0, $limit = 20) { - $parameters = [$queueName, $limit, $index]; - $types = ['string', 'integer', 'integer']; + $parameters = [$queueName, true, $limit, $index]; + $types = ['string', 'boolean', 'integer', 'integer']; - $query = 'SELECT message FROM bernard_messages WHERE queue = ? ORDER BY sentAt LIMIT ? OFFSET ?'; + $query = 'SELECT message FROM bernard_messages WHERE queue = ? AND visible = ? ORDER BY sentAt LIMIT ? OFFSET ?'; return $this ->connection diff --git a/tests/Driver/Doctrine/AbstractDriverTest.php b/tests/Driver/Doctrine/AbstractDriverTest.php index f02e9994..f4cdfa5b 100644 --- a/tests/Driver/Doctrine/AbstractDriverTest.php +++ b/tests/Driver/Doctrine/AbstractDriverTest.php @@ -134,6 +134,21 @@ public function testCountMessages() $this->assertEquals(1, $this->driver->countMessages('send-newsletter')); } + public function testPeekMessagesExcludesPoppedMessages() + { + $this->driver->pushMessage('send-newsletter', 'my-message-1'); + $this->driver->pushMessage('send-newsletter', 'my-message-2'); + $this->driver->pushMessage('send-newsletter', 'my-message-3'); + + $this->assertCount(3, $this->driver->peekQueue('send-newsletter')); + $this->assertEquals(3, $this->driver->countMessages('send-newsletter')); + + $this->driver->popMessage('send-newsletter'); + + $this->assertCount(2, $this->driver->peekQueue('send-newsletter')); + $this->assertEquals(2, $this->driver->countMessages('send-newsletter')); + } + public function testListQueues() { $this->driver->pushMessage('import', 'message1'); From 1a0f0fafeddd5c942cea1d654b379d3ad3433c4a Mon Sep 17 00:00:00 2001 From: Ben Davies Date: Wed, 4 Jul 2018 16:36:22 +0100 Subject: [PATCH 066/108] allow beberlei/assert 3 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 23e83e5b..2b03fcdb 100644 --- a/composer.json +++ b/composer.json @@ -7,7 +7,7 @@ "type": "library", "require": { "php": "^5.6 || ^7.0", - "beberlei/assert": "^2.1", + "beberlei/assert": "^2.1 || ^3.0", "bernard/normalt": "^1.0", "symfony/event-dispatcher": "^3.0 || ^4.0" }, From 7d07c175c36683b4d93d884e463833d86c260bbf Mon Sep 17 00:00:00 2001 From: Ricardo Fiorani Date: Fri, 26 Oct 2018 17:40:48 +0200 Subject: [PATCH 067/108] added test for LoggerSubscriber --- tests/EventListener/LoggerSubscriberTest.php | 52 ++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 tests/EventListener/LoggerSubscriberTest.php diff --git a/tests/EventListener/LoggerSubscriberTest.php b/tests/EventListener/LoggerSubscriberTest.php new file mode 100644 index 00000000..e82e8bf6 --- /dev/null +++ b/tests/EventListener/LoggerSubscriberTest.php @@ -0,0 +1,52 @@ +getMockBuilder(LoggerInterface::class)->getMock(); + $loggerMock->expects($this->once())->method('info'); + + $subscriber = new LoggerSubscriber($loggerMock); + $subscriber->onProduce($this->prophesize(EnvelopeEvent::class)->reveal()); + } + + public function testsLogsInfoOnInvoke() + { + $loggerMock = $this->getMockBuilder(LoggerInterface::class)->getMock(); + $loggerMock->expects($this->once())->method('info'); + + $subscriber = new LoggerSubscriber($loggerMock); + $subscriber->onInvoke($this->prophesize(EnvelopeEvent::class)->reveal()); + } + + public function testLogsErrorOnReject() + { + $loggerMock = $this->getMockBuilder(LoggerInterface::class)->getMock(); + $loggerMock->expects($this->once())->method('error'); + + $subscriber = new LoggerSubscriber($loggerMock); + $subscriber->onReject($this->prophesize(RejectEnvelopeEvent::class)->reveal()); + } + + public function testGetSubscribedEvents() + { + $events = LoggerSubscriber::getSubscribedEvents(); + $expectedEvents = [ + 'bernard.produce' => ['onProduce'], + 'bernard.invoke' => ['onInvoke'], + 'bernard.reject' => ['onReject'], + ]; + + TestCase::assertInternalType('array', $events); + TestCase::assertEquals($expectedEvents, $events); + } +} From 2877e6bb645a7045634dfeee06d2782571287c97 Mon Sep 17 00:00:00 2001 From: Maxim Mazurok Date: Wed, 12 Jun 2019 13:45:41 +0300 Subject: [PATCH 068/108] Use PhpRedisDriver in example --- example/phpredis.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/example/phpredis.php b/example/phpredis.php index 4d467774..a04e7647 100644 --- a/example/phpredis.php +++ b/example/phpredis.php @@ -1,6 +1,6 @@ connect('localhost'); $redis->setOption(Redis::OPT_PREFIX, 'bernard:'); - return new Driver($redis); + return new PhpRedisDriver($redis); } require 'bootstrap.php'; From 64d4fb15bf8a9eb62caf3e79b9cf193db3b5e8dd Mon Sep 17 00:00:00 2001 From: Menno Holtkamp Date: Sat, 12 Oct 2019 18:52:13 +0200 Subject: [PATCH 069/108] Increase compatibility with Symfony 4.3 by using proper order of parameters --- src/Producer.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/Producer.php b/src/Producer.php index 064671f1..4dc38c15 100644 --- a/src/Producer.php +++ b/src/Producer.php @@ -31,6 +31,13 @@ public function produce(Message $message, $queueName = null) $queue = $this->queues->create($queueName); $queue->enqueue($envelope = new Envelope($message)); - $this->dispatcher->dispatch(BernardEvents::PRODUCE, new EnvelopeEvent($envelope, $queue)); + $this->dispatch(BernardEvents::PRODUCE, new EnvelopeEvent($envelope, $queue)); + } + + private function dispatch($eventName, EnvelopeEvent $event) + { + $this->dispatcher instanceof \Symfony\Contracts\EventDispatcher\EventDispatcherInterface + ? $this->dispatcher->dispatch($event, $eventName) + : $this->dispatcher->dispatch($eventName, $event); } } From 41883b96b02ad996626a7386f58a5b9f19536878 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Tue, 29 Dec 2020 13:52:17 +0100 Subject: [PATCH 070/108] Add github actions Signed-off-by: Mark Sagi-Kazar --- .github/.editorconfig | 2 ++ .github/workflows/checks.yaml | 19 +++++++++++ .github/workflows/ci.yaml | 62 +++++++++++++++++++++++++++++++++++ .github/workflows/static.yaml | 22 +++++++++++++ 4 files changed, 105 insertions(+) create mode 100644 .github/.editorconfig create mode 100644 .github/workflows/checks.yaml create mode 100644 .github/workflows/ci.yaml create mode 100644 .github/workflows/static.yaml diff --git a/.github/.editorconfig b/.github/.editorconfig new file mode 100644 index 00000000..7bd3346f --- /dev/null +++ b/.github/.editorconfig @@ -0,0 +1,2 @@ +[*.yml] +indent_size = 2 diff --git a/.github/workflows/checks.yaml b/.github/workflows/checks.yaml new file mode 100644 index 00000000..5a23b55c --- /dev/null +++ b/.github/workflows/checks.yaml @@ -0,0 +1,19 @@ +name: Checks + +on: + push: + branches: + - master + pull_request: + +jobs: + composer-normalize: + name: Composer Normalize + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Composer normalize + uses: docker://ergebnis/composer-normalize-action diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 00000000..ca5cc0ab --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,62 @@ +name: CI + +on: + push: + branches: + - master + pull_request: + +jobs: + build-lowest-version: + name: Build lowest version + runs-on: ubuntu-latest + + steps: + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '5.6' + coverage: none + extensions: mbstring, intl + tools: composer:v2 + + - name: Setup Problem Matchers for PHPUnit + run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" + + - name: Checkout code + uses: actions/checkout@v2 + + - name: Download dependencies + run: composer update --no-interaction --prefer-stable --prefer-lowest --prefer-dist + + - name: Run tests + run: composer test + + build: + name: Build + runs-on: ubuntu-latest + strategy: + max-parallel: 10 + matrix: + php: ['5.6', '7.2', '7.3', '7.4'] + + steps: + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + extensions: mbstring, intl + tools: composer:v2 + + - name: Setup Problem Matchers for PHPUnit + run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" + + - name: Checkout code + uses: actions/checkout@v2 + + - name: Download dependencies + run: composer update --no-interaction --prefer-dist + + - name: Run tests + run: composer test diff --git a/.github/workflows/static.yaml b/.github/workflows/static.yaml new file mode 100644 index 00000000..f20df520 --- /dev/null +++ b/.github/workflows/static.yaml @@ -0,0 +1,22 @@ +name: Static analysis + +on: + push: + branches: + - master + pull_request: + +jobs: + php-cs-fixer: + name: PHP-CS-Fixer + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: PHP-CS-Fixer + uses: docker://oskarstark/php-cs-fixer-ga:2.16.6 + continue-on-error: true + with: + args: --dry-run --diff-format udiff From 61f0daaa025f77c3782b111155bd8a8c79b230c6 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Tue, 29 Dec 2020 14:13:35 +0100 Subject: [PATCH 071/108] Add github actions badge to readme Signed-off-by: Mark Sagi-Kazar --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 6254d23a..3edd76e6 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,7 @@

[![Latest Version](https://img.shields.io/github/release/bernardphp/bernard.svg?style=flat-square)](https://github.com/bernardphp/bernard/releases) -[![Build Status](https://img.shields.io/travis/bernardphp/bernard.svg?style=flat-square)](https://travis-ci.org/bernardphp/bernard) -[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/bernardphp/bernard.svg?style=flat-square)](https://scrutinizer-ci.com/g/bernardphp/bernard) -[![Quality Score](https://img.shields.io/scrutinizer/g/bernardphp/bernard.svg?style=flat-square)](https://scrutinizer-ci.com/g/bernardphp/bernard) +[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/bernardphp/bernard/CI?style=flat-square)](https://github.com/bernardphp/bernard/actions?query=workflow%3ACI) [![Total Downloads](https://img.shields.io/packagist/dt/bernard/bernard.svg?style=flat-square)](https://packagist.org/packages/bernard/bernard) Bernard makes it super easy and enjoyable to do background processing in PHP. From fb013f3a146f778380eaf8840db48816428b4ee1 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Tue, 29 Dec 2020 14:14:34 +0100 Subject: [PATCH 072/108] Remove unused CI files Signed-off-by: Mark Sagi-Kazar --- .scrutinizer.yml | 9 -------- .travis.yml | 59 ------------------------------------------------ 2 files changed, 68 deletions(-) delete mode 100644 .scrutinizer.yml delete mode 100644 .travis.yml diff --git a/.scrutinizer.yml b/.scrutinizer.yml deleted file mode 100644 index a5f975ba..00000000 --- a/.scrutinizer.yml +++ /dev/null @@ -1,9 +0,0 @@ -filter: - paths: [src/*] -checks: - php: - code_rating: true - duplication: true -tools: - external_code_coverage: - runs: 2 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 9337412f..00000000 --- a/.travis.yml +++ /dev/null @@ -1,59 +0,0 @@ -language: php - -sudo: false - -cache: - directories: - - $HOME/.composer/cache/files - -php: - - 5.6 - - 7.0 - - 7.1 - - 7.2 - - nightly - -services: - - mongodb - - mysql - - postgresql - -env: - global: - - TEST_COMMAND="composer test" - -matrix: - fast_finish: true - allow_failures: - - php: nightly - include: - - php: 5.6 - env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest" COVERAGE=true TEST_COMMAND="composer test-coverage" - -before_install: - - if [[ $COVERAGE != true ]]; then phpenv config-rm xdebug.ini || true; fi - - echo "extension=redis.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini - - export MONGOEXT="mongodb" - - if [[ $TRAVIS_PHP_VERSION = "5.6" ]]; then export MONGOEXT="mongo"; fi - - echo "extension=$MONGOEXT.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini - -install: - # To be removed when this issue will be resolved: https://github.com/composer/composer/issues/5355 - - if [[ "$COMPOSER_FLAGS" == *"--prefer-lowest"* ]]; then travis_retry composer update --prefer-dist --no-interaction --prefer-stable --quiet; fi - - travis_retry composer update ${COMPOSER_FLAGS} --prefer-dist --no-interaction - -before_script: - - mysql -e "CREATE DATABASE bernard_test;" - - psql -c 'CREATE DATABASE bernard_test;' -U postgres - -script: - - $TEST_COMMAND - - composer test-functional - -after_success: > - if [[ $COVERAGE = true ]]; then - wget https://scrutinizer-ci.com/ocular.phar - - php ocular.phar code-coverage:upload --format=php-clover build/spec_coverage.xml - php ocular.phar code-coverage:upload --format=php-clover build/unit_coverage.xml - fi From a0c80008467a96b55a76013a5a509085658bf0ae Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Tue, 29 Dec 2020 14:26:11 +0100 Subject: [PATCH 073/108] Upgrade required PHP version to 7.4 Signed-off-by: Mark Sagi-Kazar --- .github/workflows/ci.yaml | 4 ++-- composer.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ca5cc0ab..aad3831a 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -15,7 +15,7 @@ jobs: - name: Set up PHP uses: shivammathur/setup-php@v2 with: - php-version: '5.6' + php-version: '7.4' coverage: none extensions: mbstring, intl tools: composer:v2 @@ -38,7 +38,7 @@ jobs: strategy: max-parallel: 10 matrix: - php: ['5.6', '7.2', '7.3', '7.4'] + php: ['7.4', '8.0', '8.1'] steps: - name: Set up PHP diff --git a/composer.json b/composer.json index 2b03fcdb..d0d4a2f2 100644 --- a/composer.json +++ b/composer.json @@ -6,7 +6,7 @@ "homepage": "https://github.com/bernardphp/bernard", "type": "library", "require": { - "php": "^5.6 || ^7.0", + "php": ">=7.4", "beberlei/assert": "^2.1 || ^3.0", "bernard/normalt": "^1.0", "symfony/event-dispatcher": "^3.0 || ^4.0" From f789af2b3cda8e9c3872dc33e6bdfe38e34dcb52 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Tue, 29 Dec 2020 14:31:32 +0100 Subject: [PATCH 074/108] Upgrade dependencies to work with PHP 8.0 Signed-off-by: Mark Sagi-Kazar --- composer.json | 6 +++--- phpspec.ci.yml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index d0d4a2f2..f2288727 100644 --- a/composer.json +++ b/composer.json @@ -16,11 +16,11 @@ "doctrine/dbal": "^2.5", "doctrine/instantiator": "^1.0.5", "iron-io/iron_mq": "^4.0", - "leanphp/phpspec-code-coverage": "^3.0 || ^4.0", + "friends-of-phpspec/phpspec-code-coverage": "^6.0", "pda/pheanstalk": "^3.0", "php-amqplib/php-amqplib": "^2.5", - "phpspec/phpspec": "^3.0 || ^4.0", - "phpunit/phpunit": "^5.7 || ^6.0 || ^7.0", + "phpspec/phpspec": "^7.0", + "phpunit/phpunit": "^9.5", "predis/predis": "^1.0", "psr/container": "^1.0", "psr/log": "^1.0", diff --git a/phpspec.ci.yml b/phpspec.ci.yml index b53b4223..6b839c50 100644 --- a/phpspec.ci.yml +++ b/phpspec.ci.yml @@ -4,7 +4,7 @@ suites: psr4_prefix: Bernard formatter.name: pretty extensions: - LeanPHP\PhpSpec\CodeCoverage\CodeCoverageExtension: + FriendsOfPhpSpec\PhpSpec\CodeCoverage\CodeCoverageExtension: format: - clover output: From bf6d25b7890e2186ae8bfe1074ad0fc9b50b974c Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Tue, 29 Dec 2020 14:43:28 +0100 Subject: [PATCH 075/108] Fix code after dependency upgrade Signed-off-by: Mark Sagi-Kazar --- .gitignore | 1 + tests/Command/ConsumeCommandTest.php | 2 +- tests/Command/ProduceCommandTest.php | 7 +++---- tests/ConsumerTest.php | 10 +++++----- tests/Driver/Amqp/DriverTest.php | 2 +- tests/Driver/AppEngine/DriverTest.php | 6 +++--- tests/Driver/Doctrine/AbstractDriverTest.php | 6 +++--- .../Doctrine/Command/AbstractCommandTest.php | 2 +- .../Driver/Doctrine/Command/BaseCommandTest.php | 2 +- tests/Driver/Doctrine/ConnectionListenerTest.php | 2 +- tests/Driver/FlatFile/DriverTest.php | 6 +++--- tests/Driver/InMemory/DriverTest.php | 2 +- tests/Driver/IronMQ/DriverTest.php | 2 +- tests/Driver/MongoDB/DriverFunctionalTest.php | 4 ++-- tests/Driver/MongoDB/DriverTest.php | 2 +- tests/Driver/Pheanstalk/DriverTest.php | 2 +- tests/Driver/PhpRedis/DriverTest.php | 2 +- tests/Driver/Predis/DriverTest.php | 2 +- tests/Driver/PrefetchMessageCacheTest.php | 2 +- tests/Driver/Sqs/DriverTest.php | 9 ++++----- tests/Event/EnvelopeEventTest.php | 2 +- tests/Event/RejectEnvelopeEventTest.php | 2 +- tests/EventListener/ErrorLogSubscriberTest.php | 4 ++-- tests/EventListener/FailureSubscriberTest.php | 2 +- tests/EventListener/LoggerSubscriberTest.php | 7 +++---- tests/Message/PlainMessageTest.php | 2 +- tests/ProducerTest.php | 2 +- tests/Queue/AbstractQueueTest.php | 5 +++-- tests/Queue/InMemoryQueueTest.php | 2 +- tests/Queue/PersistentQueueTest.php | 4 ++-- tests/Queue/RoundRobinQueueTest.php | 16 +++++++--------- tests/QueueFactory/InMemoryFactoryTest.php | 7 +++---- tests/QueueFactory/PersistentFactoryTest.php | 7 +++---- 33 files changed, 65 insertions(+), 70 deletions(-) diff --git a/.gitignore b/.gitignore index 46f37ce3..47d86c7c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .php_cs .php_cs.cache +.phpunit.result.cache /_build/ /build/ /composer.lock diff --git a/tests/Command/ConsumeCommandTest.php b/tests/Command/ConsumeCommandTest.php index fda4bb47..8c8c5c54 100644 --- a/tests/Command/ConsumeCommandTest.php +++ b/tests/Command/ConsumeCommandTest.php @@ -8,7 +8,7 @@ class ConsumeCommandTest extends \PHPUnit\Framework\TestCase { - public function setUp() + public function setUp(): void { $this->queues = new InMemoryFactory(); $this->consumer = $this->getMockBuilder('Bernard\Consumer') diff --git a/tests/Command/ProduceCommandTest.php b/tests/Command/ProduceCommandTest.php index af08eda6..f3525be1 100644 --- a/tests/Command/ProduceCommandTest.php +++ b/tests/Command/ProduceCommandTest.php @@ -10,7 +10,7 @@ class ProduceCommandTest extends \PHPUnit\Framework\TestCase { protected $producer; - public function setUp() + public function setUp(): void { $this->producer = $this->getMockBuilder('Bernard\Producer') ->disableOriginalConstructor()->getMock(); @@ -29,11 +29,10 @@ public function testProduceMessageWithNoArguments() ]); } - /** - * @expectedException \RuntimeException - */ public function testInvalidJsonThrowsException() { + $this->expectException(\RuntimeException::class); + $command = new ProduceCommand($this->producer); $tester = new CommandTester($command); diff --git a/tests/ConsumerTest.php b/tests/ConsumerTest.php index da0ee78e..13fa363d 100644 --- a/tests/ConsumerTest.php +++ b/tests/ConsumerTest.php @@ -31,7 +31,7 @@ class ConsumerTest extends \PHPUnit\Framework\TestCase */ private $consumer; - public function setUp() + public function setUp(): void { $this->router = $this->prophesize(Router::class); @@ -193,11 +193,10 @@ public function testStopAfterLastMessage() $this->assertFalse($this->consumer->tick($queue, ['stop-when-empty' => true])); } - /** - * @expectedException \Bernard\Exception\ReceiverNotFoundException - */ public function testStopOnError() { + $this->expectException(\Bernard\Exception\ReceiverNotFoundException::class); + $envelope = new Envelope($message = new PlainMessage('DifferentMessageKey')); $queue = new InMemoryQueue('send-newsletter'); @@ -230,10 +229,11 @@ public function testEnvelopeWillBeInvoked() /** * @requires PHP 7.0 - * @expectedException \TypeError */ public function testWillRejectDispatchOnThrowableError() { + $this->expectException(\TypeError::class); + $envelope = new Envelope($message = new PlainMessage('ImportReport')); $queue = new InMemoryQueue('send-newsletter'); diff --git a/tests/Driver/Amqp/DriverTest.php b/tests/Driver/Amqp/DriverTest.php index 5b68594e..e8b1b55f 100644 --- a/tests/Driver/Amqp/DriverTest.php +++ b/tests/Driver/Amqp/DriverTest.php @@ -27,7 +27,7 @@ final class DriverTest extends TestCase const EXCHANGE_NAME = 'foo-exchange'; - protected function setUp() + protected function setUp(): void { $this->phpAmqpChannel = $this->getMockBuilder('\PhpAmqpLib\Channel\AMQPChannel') ->setMethods([ diff --git a/tests/Driver/AppEngine/DriverTest.php b/tests/Driver/AppEngine/DriverTest.php index 6918cb27..b0964baa 100644 --- a/tests/Driver/AppEngine/DriverTest.php +++ b/tests/Driver/AppEngine/DriverTest.php @@ -10,21 +10,21 @@ class DriverTest extends \PHPUnit\Framework\TestCase /** @var Driver */ private $driver; - public static function setUpBeforeClass() + public static function setUpBeforeClass(): void { // Very ugly hack! But AppEngine SDK isn't available outside appengine // environment. class_alias('Bernard\Tests\Fixtures\PushTask', 'google\appengine\api\taskqueue\PushTask'); } - public function setUp() + public function setUp(): void { $this->driver = new Driver([ 'send-newsletter' => '/url_endpoint', ]); } - public function tearDown() + public function tearDown(): void { PushTask::$messages = []; } diff --git a/tests/Driver/Doctrine/AbstractDriverTest.php b/tests/Driver/Doctrine/AbstractDriverTest.php index f4cdfa5b..601d1fd7 100644 --- a/tests/Driver/Doctrine/AbstractDriverTest.php +++ b/tests/Driver/Doctrine/AbstractDriverTest.php @@ -19,7 +19,7 @@ abstract class AbstractDriverTest extends \PHPUnit\Framework\TestCase */ protected $driver; - public function setUp() + public function setUp(): void { if (defined('HHVM_VERSION')) { $this->markTestSkipped('Doctrine have incompatibility issues with HHVM.'); @@ -33,7 +33,7 @@ public function setUp() $this->driver = new Driver($this->connection); } - protected function tearDown() + protected function tearDown(): void { if ($this->connection->getDatabasePlatform() instanceof MySqlPlatform) { $this->connection->exec('SET FOREIGN_KEY_CHECKS = 0'); @@ -117,7 +117,7 @@ public function testItIsAQueue() self::assertContains($message, $messages); // No messages when all are invisible - $this->assertInternalType('null', $this->driver->popMessage('import-users', 0.0001)); + $this->assertNull($this->driver->popMessage('import-users', 0.0001)); } public function testCountMessages() diff --git a/tests/Driver/Doctrine/Command/AbstractCommandTest.php b/tests/Driver/Doctrine/Command/AbstractCommandTest.php index b85d4cbb..3872399f 100644 --- a/tests/Driver/Doctrine/Command/AbstractCommandTest.php +++ b/tests/Driver/Doctrine/Command/AbstractCommandTest.php @@ -9,7 +9,7 @@ class AbstractCommandTest extends \PHPUnit\Framework\TestCase { protected $command; - public function setUp() + public function setUp(): void { $connection = $this->getMockBuilder('Doctrine\\DBAL\\Connection') ->disableOriginalConstructor()->getMock(); diff --git a/tests/Driver/Doctrine/Command/BaseCommandTest.php b/tests/Driver/Doctrine/Command/BaseCommandTest.php index e768b277..328a1a61 100644 --- a/tests/Driver/Doctrine/Command/BaseCommandTest.php +++ b/tests/Driver/Doctrine/Command/BaseCommandTest.php @@ -10,7 +10,7 @@ abstract class BaseCommandTest extends \PHPUnit\Framework\TestCase protected $sync; - public function setUp() + public function setUp(): void { $connection = $this->getMockBuilder('Doctrine\\DBAL\\Connection') ->disableOriginalConstructor()->getMock(); diff --git a/tests/Driver/Doctrine/ConnectionListenerTest.php b/tests/Driver/Doctrine/ConnectionListenerTest.php index 9ceb9a7c..84a5d04e 100644 --- a/tests/Driver/Doctrine/ConnectionListenerTest.php +++ b/tests/Driver/Doctrine/ConnectionListenerTest.php @@ -7,7 +7,7 @@ class ConnectionListenerTest extends \PHPUnit\Framework\TestCase { - protected function setUp() + protected function setUp(): void { $this->connection = $this->prophesize('Doctrine\DBAL\Connection'); diff --git a/tests/Driver/FlatFile/DriverTest.php b/tests/Driver/FlatFile/DriverTest.php index 86b14d49..da15d41e 100644 --- a/tests/Driver/FlatFile/DriverTest.php +++ b/tests/Driver/FlatFile/DriverTest.php @@ -14,7 +14,7 @@ class DriverTest extends \PHPUnit\Framework\TestCase */ private $driver; - protected function setUp() + protected function setUp(): void { $this->baseDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'bernard-flat'; @@ -25,7 +25,7 @@ protected function setUp() $this->driver = new Driver($this->baseDir); } - protected function tearDown() + protected function tearDown(): void { if ((strtoupper(substr(\PHP_OS, 0, 3)) === 'WIN')) { system('rd /s /q '.$this->baseDir); @@ -96,7 +96,7 @@ public function testPopMessageWhichPushedAfterTheInitialCollect() { $this->driver->createQueue('send-newsletter'); - $pid = pcntl_fork(); + $pid = \pcntl_fork(); if ($pid === -1) { $this->fail('Failed to fork the currently running process: ' . pcntl_strerror(pcntl_get_last_error())); diff --git a/tests/Driver/InMemory/DriverTest.php b/tests/Driver/InMemory/DriverTest.php index 75349254..0a7bb963 100644 --- a/tests/Driver/InMemory/DriverTest.php +++ b/tests/Driver/InMemory/DriverTest.php @@ -14,7 +14,7 @@ final class DriverTest extends \PHPUnit\Framework\TestCase */ private $driver; - protected function setUp() + protected function setUp(): void { $this->driver = new Driver(); } diff --git a/tests/Driver/IronMQ/DriverTest.php b/tests/Driver/IronMQ/DriverTest.php index fb0349db..e4359218 100644 --- a/tests/Driver/IronMQ/DriverTest.php +++ b/tests/Driver/IronMQ/DriverTest.php @@ -14,7 +14,7 @@ class DriverTest extends \PHPUnit\Framework\TestCase /** @var Driver */ private $driver; - public function setUp() + public function setUp(): void { $this->ironmq = $this->getMockBuilder(IronMQ::class) ->setMethods([ diff --git a/tests/Driver/MongoDB/DriverFunctionalTest.php b/tests/Driver/MongoDB/DriverFunctionalTest.php index 2eaaea27..928ddc1d 100644 --- a/tests/Driver/MongoDB/DriverFunctionalTest.php +++ b/tests/Driver/MongoDB/DriverFunctionalTest.php @@ -26,7 +26,7 @@ class DriverFunctionalTest extends \PHPUnit\Framework\TestCase /** @var Driver */ private $driver; - public function setUp() + public function setUp(): void { if (!class_exists('MongoClient')) { $this->markTestSkipped('MongoDB extension is not available.'); @@ -43,7 +43,7 @@ public function setUp() $this->driver = new Driver($this->queues, $this->messages); } - public function tearDown() + public function tearDown(): void { if (!$this->messages instanceof MongoCollection) { return; diff --git a/tests/Driver/MongoDB/DriverTest.php b/tests/Driver/MongoDB/DriverTest.php index 1db4287d..9011f384 100644 --- a/tests/Driver/MongoDB/DriverTest.php +++ b/tests/Driver/MongoDB/DriverTest.php @@ -18,7 +18,7 @@ class DriverTest extends \PHPUnit\Framework\TestCase /** @var Driver */ private $driver; - public function setUp() + public function setUp(): void { if (!class_exists('MongoCollection')) { $this->markTestSkipped('MongoDB extension is not available.'); diff --git a/tests/Driver/Pheanstalk/DriverTest.php b/tests/Driver/Pheanstalk/DriverTest.php index 67004322..97f30ff0 100644 --- a/tests/Driver/Pheanstalk/DriverTest.php +++ b/tests/Driver/Pheanstalk/DriverTest.php @@ -14,7 +14,7 @@ class DriverTest extends \PHPUnit\Framework\TestCase /** @var Driver */ private $driver; - public function setUp() + public function setUp(): void { $this->pheanstalk = $this->getMockBuilder(Pheanstalk::class) ->setMethods([ diff --git a/tests/Driver/PhpRedis/DriverTest.php b/tests/Driver/PhpRedis/DriverTest.php index 6d69dacf..3b157182 100644 --- a/tests/Driver/PhpRedis/DriverTest.php +++ b/tests/Driver/PhpRedis/DriverTest.php @@ -6,7 +6,7 @@ class DriverTest extends \PHPUnit\Framework\TestCase { - public function setUp() + public function setUp(): void { if (!extension_loaded('redis')) { $this->markTestSkipped('"redis" extension is not loaded.'); diff --git a/tests/Driver/Predis/DriverTest.php b/tests/Driver/Predis/DriverTest.php index 9744049e..cadf38e2 100644 --- a/tests/Driver/Predis/DriverTest.php +++ b/tests/Driver/Predis/DriverTest.php @@ -7,7 +7,7 @@ class DriverTest extends \Bernard\Tests\Driver\PhpRedis\DriverTest { - public function setUp() + public function setUp(): void { // Because predis uses __call all methods that needs mocking must be // explicitly defined. diff --git a/tests/Driver/PrefetchMessageCacheTest.php b/tests/Driver/PrefetchMessageCacheTest.php index f968c4b8..5eab0d51 100644 --- a/tests/Driver/PrefetchMessageCacheTest.php +++ b/tests/Driver/PrefetchMessageCacheTest.php @@ -12,6 +12,6 @@ public function testPushesAndPop() $cache->push('my-queue', ['message1', 'r0']); $this->assertEquals(['message1', 'r0'], $cache->pop('my-queue')); - $this->assertInternalType('null', $cache->pop('my-queue')); + $this->assertNull($cache->pop('my-queue')); } } diff --git a/tests/Driver/Sqs/DriverTest.php b/tests/Driver/Sqs/DriverTest.php index 86eee016..1da2d24f 100644 --- a/tests/Driver/Sqs/DriverTest.php +++ b/tests/Driver/Sqs/DriverTest.php @@ -20,7 +20,7 @@ class DriverTest extends \PHPUnit\Framework\TestCase /** @var Driver */ private $driver; - public function setUp() + public function setUp(): void { $this->sqs = $this->getMockBuilder(SqsClient::class) ->disableOriginalConstructor() @@ -123,12 +123,11 @@ public function testItCountsNumberOfMessagesInQueue() $this->assertEquals(4, $this->driver->countMessages(self::DUMMY_QUEUE_NAME)); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Queue "unknown" cannot be resolved to an url. - */ public function testUnresolveableQueueNameThrowsException() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Queue "unknown" cannot be resolved to an url.'); + $this->driver->popMessage('unknown'); } diff --git a/tests/Event/EnvelopeEventTest.php b/tests/Event/EnvelopeEventTest.php index 388b9d4b..175aaae5 100644 --- a/tests/Event/EnvelopeEventTest.php +++ b/tests/Event/EnvelopeEventTest.php @@ -8,7 +8,7 @@ class EnvelopeEventTest extends \PHPUnit\Framework\TestCase { - public function setUp() + public function setUp(): void { $message = $this->getMockBuilder(Message::class)->disableOriginalConstructor() ->getMock(); diff --git a/tests/Event/RejectEnvelopeEventTest.php b/tests/Event/RejectEnvelopeEventTest.php index 4663610b..a6813711 100644 --- a/tests/Event/RejectEnvelopeEventTest.php +++ b/tests/Event/RejectEnvelopeEventTest.php @@ -18,7 +18,7 @@ class RejectEnvelopeEventTest extends \PHPUnit\Framework\TestCase */ private $queue; - public function setUp() + public function setUp(): void { $message = $this->getMockBuilder(Message::class)->disableOriginalConstructor() ->getMock(); diff --git a/tests/EventListener/ErrorLogSubscriberTest.php b/tests/EventListener/ErrorLogSubscriberTest.php index e3f81341..28dc6501 100644 --- a/tests/EventListener/ErrorLogSubscriberTest.php +++ b/tests/EventListener/ErrorLogSubscriberTest.php @@ -17,7 +17,7 @@ class ErrorLogSubscriberTest extends \PHPUnit\Framework\TestCase private $iniErrorLog; private $errorLogFile; - public function setUp() + public function setUp(): void { if (defined('HHVM_VERSION')) { $this->markTestSkipped("HHVM does not support `ini_set('error_log', '/path/to/log')`"); @@ -35,7 +35,7 @@ public function setUp() ini_set('error_log', $this->errorLogFile); } - public function tearDown() + public function tearDown(): void { ini_set('error_log', $this->iniErrorLog); unlink($this->errorLogFile); diff --git a/tests/EventListener/FailureSubscriberTest.php b/tests/EventListener/FailureSubscriberTest.php index 8d2557e4..5929c7c0 100644 --- a/tests/EventListener/FailureSubscriberTest.php +++ b/tests/EventListener/FailureSubscriberTest.php @@ -13,7 +13,7 @@ class FailureSubscriberTest extends \PHPUnit\Framework\TestCase private $producer; private $subscriber; - public function setUp() + public function setUp(): void { $this->producer = $this->getMockBuilder('Bernard\Producer')->disableOriginalConstructor()->getMock(); $this->subscriber = new FailureSubscriber($this->producer, 'failures'); diff --git a/tests/EventListener/LoggerSubscriberTest.php b/tests/EventListener/LoggerSubscriberTest.php index e82e8bf6..c4f16160 100644 --- a/tests/EventListener/LoggerSubscriberTest.php +++ b/tests/EventListener/LoggerSubscriberTest.php @@ -5,10 +5,9 @@ use Bernard\Event\EnvelopeEvent; use Bernard\Event\RejectEnvelopeEvent; use Bernard\EventListener\LoggerSubscriber; -use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; -class LoggerSubscriberTest extends TestCase +class LoggerSubscriberTest extends \PHPUnit\Framework\TestCase { public function testLogsInfoOnProduce() { @@ -46,7 +45,7 @@ public function testGetSubscribedEvents() 'bernard.reject' => ['onReject'], ]; - TestCase::assertInternalType('array', $events); - TestCase::assertEquals($expectedEvents, $events); + $this->assertIsArray($events); + $this->assertEquals($expectedEvents, $events); } } diff --git a/tests/Message/PlainMessageTest.php b/tests/Message/PlainMessageTest.php index 7678cc12..a0186dbe 100644 --- a/tests/Message/PlainMessageTest.php +++ b/tests/Message/PlainMessageTest.php @@ -21,7 +21,7 @@ public function it_has_arguments() $this->assertEquals(1, $message['key1']); $this->assertEquals([1, 2, 3, 4], $message['key2']); - $this->assertInternalType('null', $message['key3']); + $this->assertNull($message['key3']); $this->assertTrue(isset($message->key1)); diff --git a/tests/ProducerTest.php b/tests/ProducerTest.php index 5969c930..7346d8b4 100644 --- a/tests/ProducerTest.php +++ b/tests/ProducerTest.php @@ -9,7 +9,7 @@ class ProducerTest extends \PHPUnit\Framework\TestCase { - public function setUp() + public function setUp(): void { $this->queues = new InMemoryFactory(); $this->dispatcher = new EventDispatcher(); diff --git a/tests/Queue/AbstractQueueTest.php b/tests/Queue/AbstractQueueTest.php index 1424c189..6657b685 100644 --- a/tests/Queue/AbstractQueueTest.php +++ b/tests/Queue/AbstractQueueTest.php @@ -8,11 +8,12 @@ abstract class AbstractQueueTest extends \PHPUnit\Framework\TestCase { /** * @dataProvider dataClosedMethods - * @expectedException \Bernard\Exception\InvalidOperationexception - * @expectedExceptionMessage Queue "send-newsletter" is closed. */ public function testNotAllowedWhenClosed($method, array $arguments = []) { + $this->expectException(\Bernard\Exception\InvalidOperationException::class); + $this->expectExceptionMessage('Queue "send-newsletter" is closed.'); + $queue = $this->createQueue('send-newsletter'); $queue->close(); diff --git a/tests/Queue/InMemoryQueueTest.php b/tests/Queue/InMemoryQueueTest.php index 04c4bcc8..d52a5ff3 100644 --- a/tests/Queue/InMemoryQueueTest.php +++ b/tests/Queue/InMemoryQueueTest.php @@ -17,7 +17,7 @@ public function testDequeue() $this->assertCount(1, $queue); $this->assertSame($envelope, $queue->dequeue()); $this->assertCount(0, $queue); - $this->assertInternalType('null', $queue->dequeue()); + $this->assertNull($queue->dequeue()); } public function testPeek() diff --git a/tests/Queue/PersistentQueueTest.php b/tests/Queue/PersistentQueueTest.php index de3f1bd9..6b47796a 100644 --- a/tests/Queue/PersistentQueueTest.php +++ b/tests/Queue/PersistentQueueTest.php @@ -7,7 +7,7 @@ class PersistentQueueTest extends AbstractQueueTest { - public function setUp() + public function setUp(): void { $this->driver = $this->createMock('Bernard\Driver'); $this->serializer = $this->createMock('Bernard\Serializer'); @@ -80,7 +80,7 @@ public function testDequeue() $queue = $this->createQueue('send-newsletter'); $this->assertSame($messageWrapper, $queue->dequeue()); - $this->assertInternalType('null', $queue->dequeue()); + $this->assertNull($queue->dequeue()); } /** diff --git a/tests/Queue/RoundRobinQueueTest.php b/tests/Queue/RoundRobinQueueTest.php index 7eabf0aa..1d7065a7 100644 --- a/tests/Queue/RoundRobinQueueTest.php +++ b/tests/Queue/RoundRobinQueueTest.php @@ -19,7 +19,7 @@ class RoundRobinQueueTest extends \PHPUnit\Framework\TestCase */ protected $round; - public function setUp() + public function setUp(): void { $this->queues = [ new InMemoryQueue('1'), @@ -30,12 +30,11 @@ public function setUp() $this->round = new RoundRobinQueue($this->queues); } - /** - * @expectedException \DomainException - * @expectedExceptionMessage Unrecognized queue specified: foo - */ public function testEnqueueWithUnrecognizedQueue() { + $this->expectException(\DomainException::class); + $this->expectExceptionMessage('Unrecognized queue specified: foo'); + $this->round->enqueue($this->getEnvelope('foo')); } @@ -93,12 +92,11 @@ public function testPeek() $this->assertSame([$envelope_3_1], $this->round->peek(1, 1)); } - /** - * @expectedException \DomainException - * @expectedExceptionMessage Unrecognized queue specified: foo - */ public function testAcknowledgeWithUnrecognizedQueue() { + $this->expectException(\DomainException::class); + $this->expectExceptionMessage('Unrecognized queue specified: foo'); + $envelope = $this->getEnvelope('foo'); $this->round->enqueue($envelope); $dequeued = $this->round->dequeue($envelope); diff --git a/tests/QueueFactory/InMemoryFactoryTest.php b/tests/QueueFactory/InMemoryFactoryTest.php index cc0762d3..a473798e 100644 --- a/tests/QueueFactory/InMemoryFactoryTest.php +++ b/tests/QueueFactory/InMemoryFactoryTest.php @@ -6,7 +6,7 @@ class InMemoryFactoryTest extends \PHPUnit\Framework\TestCase { - public function setUp() + public function setUp(): void { $this->factory = new InMemoryFactory(); } @@ -16,11 +16,10 @@ public function testImplementsQueueFactory() $this->assertInstanceOf('Bernard\QueueFactory', $this->factory); } - /** - * @expectedException \Bernard\Exception\InvalidOperationException - */ public function testRemoveClosesQueue() { + $this->expectException(\Bernard\Exception\InvalidOperationException::class); + $queue = $this->factory->create('queue'); $this->assertTrue($this->factory->exists('queue')); diff --git a/tests/QueueFactory/PersistentFactoryTest.php b/tests/QueueFactory/PersistentFactoryTest.php index 126cc0c3..2a7b1396 100644 --- a/tests/QueueFactory/PersistentFactoryTest.php +++ b/tests/QueueFactory/PersistentFactoryTest.php @@ -6,7 +6,7 @@ class PersistentFactoryTest extends \PHPUnit\Framework\TestCase { - public function setUp() + public function setUp(): void { $this->connection = $this->getMockBuilder('Bernard\Driver') ->disableOriginalConstructor()->getMock(); @@ -29,11 +29,10 @@ public function testItSavesQueueObjects() $this->assertSame($queue, $this->factory->create('send-newsletter')); } - /** - * @expectedException \Bernard\Exception\InvalidOperationException - */ public function testRemoveClosesQueue() { + $this->expectException(\Bernard\Exception\InvalidOperationException::class); + $this->connection->expects($this->once())->method('listQueues') ->will($this->returnValue([])); From 77da90c7409e14a1308cf4f60895d99332e9228c Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Tue, 29 Dec 2020 15:15:58 +0100 Subject: [PATCH 076/108] Drop PHP 8.1 (nightly) test target for now PHPSpec doesn't support it Signed-off-by: Mark Sagi-Kazar --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index aad3831a..f495b48d 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -38,7 +38,7 @@ jobs: strategy: max-parallel: 10 matrix: - php: ['7.4', '8.0', '8.1'] + php: ['7.4', '8.0'] steps: - name: Set up PHP From 5e25d64dc4c6123b2ee45746b8b1b9eec802cd21 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Tue, 29 Dec 2020 15:16:45 +0100 Subject: [PATCH 077/108] Add minimum php version badge Signed-off-by: Mark Sagi-Kazar --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 3edd76e6..a21b70cd 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@

[![Latest Version](https://img.shields.io/github/release/bernardphp/bernard.svg?style=flat-square)](https://github.com/bernardphp/bernard/releases) +[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%207.4-8892BF.svg?style=flat-square)](https://php.net/) [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/bernardphp/bernard/CI?style=flat-square)](https://github.com/bernardphp/bernard/actions?query=workflow%3ACI) [![Total Downloads](https://img.shields.io/packagist/dt/bernard/bernard.svg?style=flat-square)](https://packagist.org/packages/bernard/bernard) From 6988c55ef5bc823e92627c903c80c2f1688322b0 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Tue, 29 Dec 2020 15:45:21 +0100 Subject: [PATCH 078/108] Update branch alias Signed-off-by: Mark Sagi-Kazar --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index f2288727..22749279 100644 --- a/composer.json +++ b/composer.json @@ -65,7 +65,7 @@ }, "extra" : { "branch-alias" : { - "dev-master" : "1.0.x-dev" + "dev-master" : "2.0.x-dev" } }, "prefer-stable": true, From 21ebde752be81bfd4aa7e67cbd890aabb18312d9 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Tue, 29 Dec 2020 15:48:44 +0100 Subject: [PATCH 079/108] Drop relocated drivers Signed-off-by: Mark Sagi-Kazar --- composer.json | 16 +- src/Driver/Amqp/Driver.php | 174 -------------- src/Driver/Interop/Driver.php | 150 ------------ src/Driver/IronMQ/Driver.php | 154 ------------- src/Driver/Pheanstalk/Driver.php | 100 -------- src/Driver/PhpRedis/Driver.php | 119 ---------- src/Driver/Predis/Driver.php | 43 ---- src/Driver/Sqs/Driver.php | 276 ---------------------- tests/Driver/Amqp/DriverTest.php | 158 ------------- tests/Driver/Interop/DriverTest.php | 296 ------------------------ tests/Driver/IronMQ/DriverTest.php | 157 ------------- tests/Driver/Pheanstalk/DriverTest.php | 117 ---------- tests/Driver/PhpRedis/DriverTest.php | 99 -------- tests/Driver/Predis/DriverTest.php | 41 ---- tests/Driver/Sqs/DriverTest.php | 305 ------------------------- 15 files changed, 1 insertion(+), 2204 deletions(-) delete mode 100644 src/Driver/Amqp/Driver.php delete mode 100644 src/Driver/Interop/Driver.php delete mode 100644 src/Driver/IronMQ/Driver.php delete mode 100644 src/Driver/Pheanstalk/Driver.php delete mode 100644 src/Driver/PhpRedis/Driver.php delete mode 100644 src/Driver/Predis/Driver.php delete mode 100644 src/Driver/Sqs/Driver.php delete mode 100644 tests/Driver/Amqp/DriverTest.php delete mode 100644 tests/Driver/Interop/DriverTest.php delete mode 100644 tests/Driver/IronMQ/DriverTest.php delete mode 100644 tests/Driver/Pheanstalk/DriverTest.php delete mode 100644 tests/Driver/PhpRedis/DriverTest.php delete mode 100644 tests/Driver/Predis/DriverTest.php delete mode 100644 tests/Driver/Sqs/DriverTest.php diff --git a/composer.json b/composer.json index 22749279..8b6f64b1 100644 --- a/composer.json +++ b/composer.json @@ -12,32 +12,18 @@ "symfony/event-dispatcher": "^3.0 || ^4.0" }, "require-dev" : { - "aws/aws-sdk-php": "^3.0", "doctrine/dbal": "^2.5", "doctrine/instantiator": "^1.0.5", - "iron-io/iron_mq": "^4.0", "friends-of-phpspec/phpspec-code-coverage": "^6.0", - "pda/pheanstalk": "^3.0", - "php-amqplib/php-amqplib": "^2.5", "phpspec/phpspec": "^7.0", "phpunit/phpunit": "^9.5", - "predis/predis": "^1.0", "psr/container": "^1.0", "psr/log": "^1.0", - "queue-interop/amqp-interop": "^0.6", - "queue-interop/queue-interop": "^0.6", "symfony/console": "^3.0 || ^4.0" }, "suggest": { - "php-amqplib/php-amqplib": "Allow sending messages to an AMQP server using php-amqplib", "doctrine/dbal": "Allow sending messages to simulated message queue in a database via doctrine dbal", - "iron-io/iron_mq": "Allow sending messages to IronMQ", - "pda/pheanstalk": "Allow sending messages to Beanstalk using pheanstalk", - "predis/predis": "Allow sending messages to Redis using predis", - "aws/aws-sdk-php": "Allow sending messages to AWS services like Simple Queue Service", - "mongodb/mongodb": "Allow sending messages to a MongoDB server via PHP Driver", - "queue-interop/queue-interop": "Allow sending messages using queue interop compatible transports", - "queue-interop/amqp-interop": "Allow sending messages using amqp interop compatible transports" + "mongodb/mongodb": "Allow sending messages to a MongoDB server via PHP Driver" }, "autoload" : { "psr-4" : { "Bernard\\" : "src/" } diff --git a/src/Driver/Amqp/Driver.php b/src/Driver/Amqp/Driver.php deleted file mode 100644 index 4926a7c6..00000000 --- a/src/Driver/Amqp/Driver.php +++ /dev/null @@ -1,174 +0,0 @@ -connection = $connection; - $this->exchange = $exchange; - $this->defaultMessageParams = $defaultMessageParams; - } - - /** - * Returns a list of all queue names. - * - * @return array - */ - public function listQueues() - { - } - - /** - * Create a queue. - * - * @param string $queueName - */ - public function createQueue($queueName) - { - $channel = $this->getChannel(); - $channel->exchange_declare($this->exchange, 'direct', false, true, false); - $channel->queue_declare($queueName, false, true, false, false); - $channel->queue_bind($queueName, $this->exchange, $queueName); - } - - /** - * Count the number of messages in queue. This can be a approximately number. - * - * @param string $queueName - * - * @return int - */ - public function countMessages($queueName) - { - list(, $messageCount) = $this->getChannel()->queue_declare($queueName, true); - - return $messageCount; - } - - /** - * Insert a message at the top of the queue. - * - * @param string $queueName - * @param string $message - */ - public function pushMessage($queueName, $message) - { - $amqpMessage = new AMQPMessage($message, $this->defaultMessageParams); - $this->getChannel()->basic_publish($amqpMessage, $this->exchange, $queueName); - } - - /** - * Remove the next message in line. And if no message is available - * wait $duration seconds. - * - * @param string $queueName - * @param int $duration - * - * @return array An array like array($message, $receipt); - */ - public function popMessage($queueName, $duration = 5) - { - $runtime = microtime(true) + $duration; - - while (microtime(true) < $runtime) { - $message = $this->getChannel()->basic_get($queueName); - - if ($message) { - return [$message->body, $message->get('delivery_tag')]; - } - - // sleep for 10 ms to prevent hammering CPU - usleep(10000); - } - - return [null, null]; - } - - /** - * If the driver supports it, this will be called when a message - * have been consumed. - * - * @param string $queueName - * @param mixed $receipt - */ - public function acknowledgeMessage($queueName, $receipt) - { - $this->getChannel()->basic_ack($receipt); - } - - /** - * Returns a $limit numbers of messages without removing them - * from the queue. - * - * @param string $queueName - * @param int $index - * @param int $limit - */ - public function peekQueue($queueName, $index = 0, $limit = 20) - { - } - - /** - * Removes the queue. - * - * @param string $queueName - */ - public function removeQueue($queueName) - { - $this->getChannel()->queue_delete($queueName); - } - - /** - * @return array - */ - public function info() - { - } - - public function __destruct() - { - if (null !== $this->channel) { - $this->channel->close(); - } - } - - private function getChannel() - { - if (null === $this->channel) { - $this->channel = $this->connection->channel(); - } - - return $this->channel; - } -} diff --git a/src/Driver/Interop/Driver.php b/src/Driver/Interop/Driver.php deleted file mode 100644 index acf580dc..00000000 --- a/src/Driver/Interop/Driver.php +++ /dev/null @@ -1,150 +0,0 @@ -context = $context; - - $this->consumers = []; - } - - /** - * {@inheritdoc} - */ - public function listQueues() - { - return []; - } - - /** - * {@inheritdoc} - */ - public function createQueue($queueName) - { - if ($this->context instanceof AmqpContext) { - $this->context->declareQueue($this->createAmqpQueue($queueName)); - } - } - - /** - * {@inheritdoc} - */ - public function countMessages($queueName) - { - if ($this->context instanceof AmqpContext) { - return $this->context->declareQueue($this->createAmqpQueue($queueName)); - } - - return 0; - } - - /** - * {@inheritdoc} - */ - public function pushMessage($queueName, $message) - { - $queue = $this->context->createQueue($queueName); - $message = $this->context->createMessage($message); - - $this->context->createProducer()->send($queue, $message); - } - - /** - * {@inheritdoc} - */ - public function popMessage($queueName, $duration = 5) - { - if ($message = $this->getQueueConsumer($queueName)->receive($duration * 1000)) { - return [$message->getBody(), $message]; - } - } - - /** - * {@inheritdoc} - */ - public function acknowledgeMessage($queueName, $receipt) - { - $this->getQueueConsumer($queueName)->acknowledge($receipt); - } - - /** - * {@inheritdoc} - */ - public function peekQueue($queueName, $index = 0, $limit = 20) - { - return []; - } - - /** - * {@inheritdoc} - */ - public function removeQueue($queueName) - { - if ($this->context instanceof AmqpContext) { - $queue = $this->createAmqpQueue($queueName); - - $this->context->deleteQueue($queue); - } - } - - /** - * {@inheritdoc} - */ - public function info() - { - return []; - } - - /** - * @param string $queueName - * - * @return PsrConsumer - */ - private function getQueueConsumer($queueName) - { - if (false == array_key_exists($queueName, $this->consumers)) { - $queue = $this->context->createQueue($queueName); - - $this->consumers[$queueName] = $this->context->createConsumer($queue); - } - - return $this->consumers[$queueName]; - } - - /** - * @param string $queueName - * - * @return AmqpQueue - */ - private function createAmqpQueue($queueName) - { - /** @var AmqpContext $context */ - $context = $this->context; - - $queue = $context->createQueue($queueName); - $queue->addFlag(AmqpQueue::FLAG_DURABLE); - - return $queue; - } -} diff --git a/src/Driver/IronMQ/Driver.php b/src/Driver/IronMQ/Driver.php deleted file mode 100644 index a86312e9..00000000 --- a/src/Driver/IronMQ/Driver.php +++ /dev/null @@ -1,154 +0,0 @@ -ironmq = $ironmq; - } - - /** - * {@inheritdoc} - */ - public function listQueues() - { - $queueNames = []; - $page = 0; - - while ($queues = $this->ironmq->getQueues($page, 100)) { - $queueNames += $this->pluck($queues, 'name'); - - // If we get 100 results the probability of another page is high. - if (count($queues) < 100) { - break; - } - - ++$page; - } - - return $queueNames; - } - - /** - * {@inheritdoc} - */ - public function createQueue($queueName) - { - } - - /** - * {@inheritdoc} - */ - public function countMessages($queueName) - { - if ($info = $this->ironmq->getQueue($queueName)) { - return $info->size; - } - } - - /** - * {@inheritdoc} - */ - public function pushMessage($queueName, $message) - { - $this->ironmq->postMessage($queueName, $message); - } - - /** - * {@inheritdoc} - */ - public function popMessage($queueName, $duration = 5) - { - if ($message = $this->cache->pop($queueName)) { - return $message; - } - - $timeout = IronMQ::GET_MESSAGE_TIMEOUT; - - $messages = $this->ironmq->getMessages($queueName, $this->prefetch, $timeout, $duration); - - if (!$messages) { - return [null, null]; - } - - foreach ($messages as $message) { - $this->cache->push($queueName, [$message->body, $message->id]); - } - - return $this->cache->pop($queueName); - } - - /** - * {@inheritdoc} - */ - public function acknowledgeMessage($queueName, $receipt) - { - $this->ironmq->deleteMessage($queueName, $receipt); - } - - /** - * IronMQ does not support an offset when peeking messages. - * - * {@inheritdoc} - */ - public function peekQueue($queueName, $index = 0, $limit = 20) - { - if ($messages = $this->ironmq->peekMessages($queueName, $limit)) { - return $this->pluck($messages, 'body'); - } - - return []; - } - - /** - * {@inheritdoc} - */ - public function removeQueue($queueName) - { - $this->ironmq->deleteQueue($queueName); - } - - /** - * {@inheritdoc} - */ - public function info() - { - return [ - 'prefetch' => $this->prefetch, - ]; - } - - /** - * The missing array_pluck but for objects array. - * - * @param array $objects - * @param string $property - * - * @return array - */ - protected function pluck(array $objects, $property) - { - $function = function ($object) use ($property) { - return $object->$property; - }; - - return array_map($function, $objects); - } -} diff --git a/src/Driver/Pheanstalk/Driver.php b/src/Driver/Pheanstalk/Driver.php deleted file mode 100644 index a91486e8..00000000 --- a/src/Driver/Pheanstalk/Driver.php +++ /dev/null @@ -1,100 +0,0 @@ -pheanstalk = $pheanstalk; - } - - /** - * {@inheritdoc} - */ - public function listQueues() - { - return $this->pheanstalk->listTubes(); - } - - /** - * {@inheritdoc} - */ - public function createQueue($queueName) - { - } - - /** - * {@inheritdoc} - */ - public function countMessages($queueName) - { - $stats = $this->pheanstalk->statsTube($queueName); - - return $stats['current-jobs-ready']; - } - - /** - * {@inheritdoc} - */ - public function pushMessage($queueName, $message) - { - $this->pheanstalk->putInTube($queueName, $message); - } - - /** - * {@inheritdoc} - */ - public function popMessage($queueName, $duration = 5) - { - if ($job = $this->pheanstalk->reserveFromTube($queueName, $duration)) { - return [$job->getData(), $job]; - } - - return [null, null]; - } - - /** - * {@inheritdoc} - */ - public function acknowledgeMessage($queueName, $receipt) - { - $this->pheanstalk->delete($receipt); - } - - /** - * {@inheritdoc} - */ - public function peekQueue($queueName, $index = 0, $limit = 20) - { - return []; - } - - /** - * {@inheritdoc} - */ - public function removeQueue($queueName) - { - } - - /** - * {@inheritdoc} - */ - public function info() - { - return $this->pheanstalk - ->stats() - ->getArrayCopy() - ; - } -} diff --git a/src/Driver/PhpRedis/Driver.php b/src/Driver/PhpRedis/Driver.php deleted file mode 100644 index 9234feca..00000000 --- a/src/Driver/PhpRedis/Driver.php +++ /dev/null @@ -1,119 +0,0 @@ -redis = $redis; - } - - /** - * {@inheritdoc} - */ - public function listQueues() - { - return $this->redis->sMembers('queues'); - } - - /** - * {@inheritdoc} - */ - public function createQueue($queueName) - { - $this->redis->sAdd('queues', $queueName); - } - - /** - * {@inheritdoc} - */ - public function countMessages($queueName) - { - return $this->redis->lLen(self::QUEUE_PREFIX.$queueName); - } - - /** - * {@inheritdoc} - */ - public function pushMessage($queueName, $message) - { - $this->redis->rpush($this->resolveKey($queueName), $message); - } - - /** - * {@inheritdoc} - */ - public function popMessage($queueName, $duration = 5) - { - // When PhpRedis is set up with an Redis::OPT_PREFIX - // it does set the prefix to the key and to the timeout value something like: - // "BLPOP" "bernard:queue:my-queue" "bernard:5" - // - // To set the resolved key in an array seems fixing this issue. We get: - // "BLPOP" "bernard:queue:my-queue" "5" - // - // see https://github.com/nicolasff/phpredis/issues/158 - list(, $message) = $this->redis->blpop([$this->resolveKey($queueName)], $duration) ?: null; - - return [$message, null]; - } - - /** - * {@inheritdoc} - */ - public function peekQueue($queueName, $index = 0, $limit = 20) - { - $limit += $index - 1; - - return $this->redis->lRange($this->resolveKey($queueName), $index, $limit); - } - - /** - * {@inheritdoc} - */ - public function acknowledgeMessage($queueName, $receipt) - { - } - - /** - * {@inheritdoc} - */ - public function removeQueue($queueName) - { - $this->redis->sRem('queues', $queueName); - $this->redis->del($this->resolveKey($queueName)); - } - - /** - * {@inheritdoc} - */ - public function info() - { - return $this->redis->info(); - } - - /** - * Transform the queueName into a key. - * - * @param string $queueName - * - * @return string - */ - protected function resolveKey($queueName) - { - return self::QUEUE_PREFIX.$queueName; - } -} diff --git a/src/Driver/Predis/Driver.php b/src/Driver/Predis/Driver.php deleted file mode 100644 index dc2afead..00000000 --- a/src/Driver/Predis/Driver.php +++ /dev/null @@ -1,43 +0,0 @@ -redis = $redis; - } - - /** - * {@inheritdoc} - */ - public function popMessage($queueName, $duration = 5) - { - list(, $message) = $this->redis->blpop($this->resolveKey($queueName), $duration) ?: null; - - return [$message, null]; - } - - /** - * {@inheritdoc} - */ - public function info() - { - // Temporarily change the command use to get info as earlier and newer redis - // versions breaks it into sections. - $commandClass = $this->redis->getProfile()->getCommandClass('info'); - $this->redis->getProfile()->defineCommand('info', 'Predis\Command\ServerInfo'); - - $info = $this->redis->info(); - - $this->redis->getProfile()->defineCommand('info', $commandClass); - - return $info; - } -} diff --git a/src/Driver/Sqs/Driver.php b/src/Driver/Sqs/Driver.php deleted file mode 100644 index aa7dacec..00000000 --- a/src/Driver/Sqs/Driver.php +++ /dev/null @@ -1,276 +0,0 @@ -sqs = $sqs; - $this->queueUrls = $queueUrls; - } - - /** - * {@inheritdoc} - */ - public function listQueues() - { - $result = $this->sqs->listQueues(); - - if (!$queueUrls = $result->get('QueueUrls')) { - return array_keys($this->queueUrls); - } - - foreach ($queueUrls as $queueUrl) { - if (in_array($queueUrl, $this->queueUrls)) { - continue; - } - - $queueName = current(array_reverse(explode('/', $queueUrl))); - $this->queueUrls[$queueName] = $queueUrl; - } - - return array_keys($this->queueUrls); - } - - /** - * {@inheritdoc} - * - * @see http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#createqueue - * - * @throws SqsException - */ - public function createQueue($queueName) - { - if ($this->queueExists($queueName)) { - return; - } - - $parameters = [ - 'QueueName' => $queueName, - ]; - - if ($this->isFifoQueue($queueName)) { - $parameters['Attributes'] = [ - 'FifoQueue' => 'true', - ]; - } - - $result = $this->sqs->createQueue($parameters); - - $this->queueUrls[$queueName] = $result['QueueUrl']; - } - - /** - * @param string $queueName - * - * @return bool - * - * @throws SqsException - */ - private function queueExists($queueName) - { - try { - $this->resolveUrl($queueName); - - return true; - } catch (\InvalidArgumentException $exception) { - return false; - } catch (SqsException $exception) { - if ($previousException = $exception->getPrevious()) { - switch ($previousException->getCode()) { - case self::AWS_SQS_EXCEPTION_BAD_REQUEST: - case self::AWS_SQS_EXCEPTION_NOT_FOUND: - return false; - } - } - - throw $exception; - } - } - - /** - * @param string $queueName - * - * @return bool - */ - private function isFifoQueue($queueName) - { - return $this->endsWith($queueName, self::AWS_SQS_FIFO_SUFFIX); - } - - /** - * @param string $haystack - * @param string $needle - * - * @return bool - */ - private function endsWith($haystack, $needle) - { - $length = strlen($needle); - if ($length === 0) { - return true; - } - - return substr($haystack, -$length) === $needle; - } - - /** - * {@inheritdoc} - */ - public function countMessages($queueName) - { - $queueUrl = $this->resolveUrl($queueName); - - $result = $this->sqs->getQueueAttributes([ - 'QueueUrl' => $queueUrl, - 'AttributeNames' => ['ApproximateNumberOfMessages'], - ]); - - if (isset($result['Attributes']['ApproximateNumberOfMessages'])) { - return (int) $result['Attributes']['ApproximateNumberOfMessages']; - } - - return 0; - } - - /** - * {@inheritdoc} - */ - public function pushMessage($queueName, $message) - { - $queueUrl = $this->resolveUrl($queueName); - - $parameters = [ - 'QueueUrl' => $queueUrl, - 'MessageBody' => $message, - ]; - - if ($this->isFifoQueue($queueName)) { - $parameters['MessageGroupId'] = __METHOD__; - $parameters['MessageDeduplicationId'] = md5($message); - } - - $this->sqs->sendMessage($parameters); - } - - /** - * {@inheritdoc} - */ - public function popMessage($queueName, $duration = 5) - { - if ($message = $this->cache->pop($queueName)) { - return $message; - } - - $queueUrl = $this->resolveUrl($queueName); - - $result = $this->sqs->receiveMessage([ - 'QueueUrl' => $queueUrl, - 'MaxNumberOfMessages' => $this->prefetch, - 'WaitTimeSeconds' => $duration, - ]); - - if (!$result || !$messages = $result->get('Messages')) { - return [null, null]; - } - - foreach ($messages as $message) { - $this->cache->push($queueName, [$message['Body'], $message['ReceiptHandle']]); - } - - return $this->cache->pop($queueName); - } - - /** - * {@inheritdoc} - */ - public function acknowledgeMessage($queueName, $receipt) - { - $queueUrl = $this->resolveUrl($queueName); - - $this->sqs->deleteMessage([ - 'QueueUrl' => $queueUrl, - 'ReceiptHandle' => $receipt, - ]); - } - - /** - * {@inheritdoc} - */ - public function peekQueue($queueName, $index = 0, $limit = 20) - { - return []; - } - - /** - * {@inheritdoc} - * - * @see http://docs.aws.amazon.com/aws-sdk-php/v3/api/api-sqs-2012-11-05.html#deletequeue - */ - public function removeQueue($queueName) - { - $queueUrl = $this->resolveUrl($queueName); - - $this->sqs->deleteQueue([ - 'QueueUrl' => $queueUrl, - ]); - } - - /** - * {@inheritdoc} - */ - public function info() - { - return [ - 'prefetch' => $this->prefetch, - ]; - } - - /** - * AWS works with queue URLs rather than queue names. Returns either queue URL (if queue exists) for given name or null if not. - * - * @param string $queueName - * - * @return mixed - * - * @throws SqsException - */ - private function resolveUrl($queueName) - { - if (isset($this->queueUrls[$queueName])) { - return $this->queueUrls[$queueName]; - } - - $result = $this->sqs->getQueueUrl(['QueueName' => $queueName]); - - if ($result && $queueUrl = $result->get('QueueUrl')) { - return $this->queueUrls[$queueName] = $queueUrl; - } - - throw new \InvalidArgumentException('Queue "'.$queueName.'" cannot be resolved to an url.'); - } -} diff --git a/tests/Driver/Amqp/DriverTest.php b/tests/Driver/Amqp/DriverTest.php deleted file mode 100644 index e8b1b55f..00000000 --- a/tests/Driver/Amqp/DriverTest.php +++ /dev/null @@ -1,158 +0,0 @@ -phpAmqpChannel = $this->getMockBuilder('\PhpAmqpLib\Channel\AMQPChannel') - ->setMethods([ - 'basic_publish', - 'basic_get', - 'basic_ack', - 'exchange_declare', - 'queue_declare', - 'queue_bind', - ]) - ->disableOriginalConstructor() - ->getMock(); - - $this->phpAmqpConnection = $this->getMockBuilder('\PhpAmqpLib\Connection\AMQPStreamConnection') - ->setMethods([ - 'channel', - ]) - ->disableOriginalConstructor() - ->getMock(); - - $this->phpAmqpConnection - ->expects($this->any()) - ->method('channel') - ->willReturn($this->phpAmqpChannel); - - $this->driver = new Driver($this->phpAmqpConnection, self::EXCHANGE_NAME); - } - - public function testItImplementsDriverInterface() - { - $this->assertInstanceOf('Bernard\Driver', $this->driver); - } - - public function testItCreatesQueue() - { - $this->phpAmqpChannel - ->expects($this->once()) - ->method('exchange_declare') - ->with(self::EXCHANGE_NAME, 'direct', false, true, false); - $this->phpAmqpChannel - ->expects($this->once()) - ->method('queue_declare') - ->with('foo-queue', false, true, false, false); - $this->phpAmqpChannel - ->expects($this->once()) - ->method('queue_bind') - ->with('foo-queue', self::EXCHANGE_NAME, 'foo-queue'); - - $this->driver->createQueue('foo-queue'); - } - - public function testItPushesMessages() - { - $this->phpAmqpChannel - ->expects($this->once()) - ->method('basic_publish') - ->with( - $this->callback(function (AMQPMessage $message) { - return $message->body === 'dummy push message'; - }), - self::EXCHANGE_NAME, - 'not-relevant' - ); - $this->driver->pushMessage('not-relevant', 'dummy push message'); - } - - public function testItUsesDefaultParameters() - { - $this->driver = new Driver( - $this->phpAmqpConnection, - self::EXCHANGE_NAME, - ['delivery_mode' => 2] - ); - - $this->phpAmqpChannel - ->expects($this->once()) - ->method('basic_publish') - ->with( - $this->callback(function (AMQPMessage $message) { - return $message->get('delivery_mode') === 2; - }), - self::EXCHANGE_NAME, - 'not-relevant' - ); - $this->driver->pushMessage('not-relevant', 'dummy push message'); - } - - public function testItPopsMessages() - { - $amqpMessage = new AMQPMessage('bar'); - $amqpMessage->delivery_info['delivery_tag'] = 'alright'; - - $this->phpAmqpChannel - ->expects($this->once()) - ->method('basic_get') - ->with($this->equalTo('foo-queue')) - ->willReturn($amqpMessage); - - $this->assertEquals(['bar', 'alright'], $this->driver->popMessage('foo-queue')); - } - - public function testItPopsArrayWithNullsWhenThereAreNoMessages() - { - $startTime = microtime(true); - - $this->phpAmqpChannel - ->expects($this->any()) - ->method('basic_get') - ->with($this->equalTo('foo-queue')) - ->willReturn(null); - - $result = $this->driver->popMessage('foo-queue', 0.1); - $duration = microtime(true) - $startTime; - - $this->assertEquals([null, null], $result); - $this->assertGreaterThan(0.1, $duration); - } - - public function testItAcknowledgesMessage() - { - $this->phpAmqpChannel - ->expects($this->once()) - ->method('basic_ack') - ->with('delivery-tag'); - - $this->driver->acknowledgeMessage('irrelevant', 'delivery-tag'); - } -} diff --git a/tests/Driver/Interop/DriverTest.php b/tests/Driver/Interop/DriverTest.php deleted file mode 100644 index f11fe460..00000000 --- a/tests/Driver/Interop/DriverTest.php +++ /dev/null @@ -1,296 +0,0 @@ -assertInstanceOf('Bernard\Driver', new Driver($this->createInteropContextMock())); - } - - public function testListQueuesMethodDoesNothingAndAlwaysReturnEmptyArray() - { - $driver = new Driver($this->createInteropContextMock()); - - $this->assertSame([], $driver->listQueues()); - } - - public function testCreateQueueMethodDoesNothingAndAlwaysReturnNull() - { - $driver = new Driver($this->createInteropContextMock()); - - $this->assertNull($driver->createQueue('aQueueName')); - } - - public function testPushMessageMethodPublishMessageToQueueUsingInteropProducer() - { - $queue = $this->createMock(PsrQueue::class); - $message = $this->createMock(PsrMessage::class); - - $producer = $this->createMock(PsrProducer::class); - $producer - ->expects($this->once()) - ->method('send') - ->with($this->identicalTo($queue), $this->identicalTo($message)) - ; - - $context = $this->createInteropContextMock(); - $context - ->expects($this->once()) - ->method('createQueue') - ->with('theQueueName') - ->willReturn($queue) - ; - $context - ->expects($this->once()) - ->method('createMessage') - ->with('theBody') - ->willReturn($message) - ; - $context - ->expects($this->once()) - ->method('createProducer') - ->willReturn($producer) - ; - - $driver = new Driver($context); - - $driver->pushMessage('theQueueName', 'theBody'); - } - - public function testPopMessageReturnNullIfInteropConsumerReturnNothingOnReceive() - { - $queue = $this->createMock(PsrQueue::class); - - $consumer = $this->createMock(PsrConsumer::class); - $consumer - ->expects($this->once()) - ->method('receive') - ->with(5000) - ->willReturn(null) - ; - - $context = $this->createInteropContextMock(); - $context - ->expects($this->once()) - ->method('createQueue') - ->with('theQueueName') - ->willReturn($queue) - ; - $context - ->expects($this->once()) - ->method('createConsumer') - ->with($this->identicalTo($queue)) - ->willReturn($consumer) - ; - - $driver = new Driver($context); - - $this->assertNull($driver->popMessage('theQueueName')); - } - - public function testPopMessageReturnArrayWithBodyAndInteropMessage() - { - $queue = $this->createMock(PsrQueue::class); - $message = $this->createMock(PsrMessage::class); - $message - ->expects($this->once()) - ->method('getBody') - ->willReturn('theBody') - ; - - $consumer = $this->createMock(PsrConsumer::class); - $consumer - ->expects($this->once()) - ->method('receive') - ->with(6789) - ->willReturn($message) - ; - - $context = $this->createInteropContextMock(); - $context - ->expects($this->once()) - ->method('createQueue') - ->with('theQueueName') - ->willReturn($queue) - ; - $context - ->expects($this->once()) - ->method('createConsumer') - ->with($this->identicalTo($queue)) - ->willReturn($consumer) - ; - - $driver = new Driver($context); - - $this->assertSame( - ['theBody', $message], - $driver->popMessage('theQueueName', 6.789) - ); - } - - public function testAcknowledgeMessage() - { - $queue = $this->createMock(PsrQueue::class); - $message = $this->createMock(PsrMessage::class); - - $consumer = $this->createMock(PsrConsumer::class); - $consumer - ->expects($this->once()) - ->method('receive') - ->willReturn($message) - ; - $consumer - ->expects($this->once()) - ->method('acknowledge') - ->with($this->identicalTo($message)) - ; - - $context = $this->createInteropContextMock(); - $context - ->expects($this->once()) - ->method('createQueue') - ->with('theQueueName') - ->willReturn($queue) - ; - $context - ->expects($this->once()) - ->method('createConsumer') - ->with($this->identicalTo($queue)) - ->willReturn($consumer) - ; - - $driver = new Driver($context); - - $result = $driver->popMessage('theQueueName'); - - //guard - $this->assertSame($message, $result[1]); - - $driver->acknowledgeMessage('theQueueName', $result[1]); - } - - public function testPeekQueueMethodDoesNothingAndAlwaysReturnEmptyArray() - { - $driver = new Driver($this->createInteropContextMock()); - - $this->assertSame([], $driver->peekQueue('aQueueName')); - } - - public function testRemoveQueueMethodDoesNothingAndAlwaysReturnNull() - { - $driver = new Driver($this->createInteropContextMock()); - - $this->assertNull($driver->removeQueue('aQueueName')); - } - - public function testInfoMethodDoesNothingAndAlwaysReturnEmptyArray() - { - $driver = new Driver($this->createInteropContextMock()); - - $this->assertNull($driver->removeQueue('aQueueName')); - } - - public function testCreateQueueMethodShouldDeclareAmqpQueue() - { - $queue = $this->createMock(AmqpQueue::class); - $queue - ->expects($this->once()) - ->method('addFlag') - ->with(AmqpQueue::FLAG_DURABLE) - ; - - $context = $this->createAmqpInteropContextMock(); - $context - ->expects($this->once()) - ->method('createQueue') - ->with('theQueueName') - ->willReturn($queue) - ; - $context - ->expects($this->once()) - ->method('declareQueue') - ->with($this->identicalTo($queue)) - ; - - $driver = new Driver($context); - - $this->assertNull($driver->createQueue('theQueueName')); - } - - public function testDeleteQueueMethodShouldCallDeleteQueueMethodOnAmqpContext() - { - $queue = $this->createMock(AmqpQueue::class); - $queue - ->expects($this->once()) - ->method('addFlag') - ->with(AmqpQueue::FLAG_DURABLE) - ; - - $context = $this->createAmqpInteropContextMock(); - $context - ->expects($this->once()) - ->method('createQueue') - ->with('theQueueName') - ->willReturn($queue) - ; - $context - ->expects($this->once()) - ->method('deleteQueue') - ->with($this->identicalTo($queue)) - ; - - $driver = new Driver($context); - - $this->assertNull($driver->removeQueue('theQueueName')); - } - - public function testCountMessagesMethodShouldUseCountFromAmqpDeclareQueueResult() - { - $queue = $this->createMock(AmqpQueue::class); - - $context = $this->createAmqpInteropContextMock(); - $context - ->expects($this->once()) - ->method('createQueue') - ->with('theQueueName') - ->willReturn($queue) - ; - $context - ->expects($this->once()) - ->method('declareQueue') - ->with($this->identicalTo($queue)) - ->willReturn(123) - ; - - $driver = new Driver($context); - - $this->assertSame(123, $driver->countMessages('theQueueName')); - } - - /** - * @return \PHPUnit_Framework_MockObject_MockObject|AmqpContext - */ - private function createAmqpInteropContextMock() - { - return $this->createMock(AmqpContext::class); - } - - /** - * @return \PHPUnit_Framework_MockObject_MockObject|PsrContext - */ - private function createInteropContextMock() - { - return $this->createMock(PsrContext::class); - } -} diff --git a/tests/Driver/IronMQ/DriverTest.php b/tests/Driver/IronMQ/DriverTest.php deleted file mode 100644 index e4359218..00000000 --- a/tests/Driver/IronMQ/DriverTest.php +++ /dev/null @@ -1,157 +0,0 @@ -ironmq = $this->getMockBuilder(IronMQ::class) - ->setMethods([ - 'getQueue', - 'getQueues', - 'peekMessages', - 'deleteQueue', - 'postMessage', - 'getMessages', - 'deleteMessage', - ]) - ->disableOriginalConstructor() - ->getMock(); - - $this->driver = new Driver($this->ironmq); - } - - public function testItExposesInfo() - { - $driver = new Driver($this->ironmq, 10); - - $this->assertEquals(['prefetch' => 10], $driver->info()); - $this->assertEquals(['prefetch' => 2], $this->driver->info()); - } - - public function testItImplementsDriverInterface() - { - $this->assertInstanceOf(AbstractPrefetchDriver::class, $this->driver); - } - - public function testItCountsNumberOfMessagesInQueue() - { - $this->ironmq->expects($this->at(0))->method('getQueue') - ->with($this->equalTo('send-newsletter'))->will($this->returnValue((object) ['size' => 4])); - - $this->ironmq->expects($this->at(1))->method('getQueue') - ->with($this->equalTo('non-existant'))->will($this->returnValue(null)); - - $this->assertEquals(4, $this->driver->countMessages('send-newsletter')); - $this->assertEquals(null, $this->driver->countMessages('non-existant')); - } - - public function testItListQueues() - { - $ironmqQueues = [ - (object) ['name' => 'failed'], - (object) ['name' => 'queue1'], - ]; - - $this->ironmq->expects($this->once())->method('getQueues') - ->will($this->returnValue($ironmqQueues)); - - $this->assertEquals(['failed', 'queue1'], $this->driver->listQueues()); - } - - public function testAcknowledgeMessage() - { - $this->ironmq->expects($this->once())->method('deleteMessage') - ->with($this->equalTo('my-queue'), $this->equalTo('receipt1')); - - $this->driver->acknowledgeMessage('my-queue', 'receipt1'); - } - - public function testItPeeksInAQueue() - { - $ironmqMessages = [ - (object) ['body' => 'message1'], - ]; - - $this->ironmq->expects($this->at(0))->method('peekMessages') - ->with($this->equalTo('my-queue'), $this->equalTo(10))->will($this->returnValue($ironmqMessages)); - $this->ironmq->expects($this->at(1))->method('peekMessages') - ->with($this->equalTo('my-queue2'), $this->equalTo(20))->will($this->returnValue(null)); - - $this->assertEquals(['message1'], $this->driver->peekQueue('my-queue', 10, 10)); - $this->assertEquals([], $this->driver->peekQueue('my-queue2')); - } - - public function testItRemovesAQueue() - { - $this->ironmq - ->expects($this->once()) - ->method('deleteQueue') - ->with($this->equalTo('my-queue')); - - $this->driver->removeQueue('my-queue'); - } - - public function testItPushesMessages() - { - $this->ironmq - ->expects($this->once()) - ->method('postMessage') - ->with($this->equalTo('my-queue'), $this->equalTo('This is a message')); - - $this->driver->pushMessage('my-queue', 'This is a message'); - } - - public function testItPrefetchesMessages() - { - $ironmqMessages = [ - (object) ['body' => 'message1', 'id' => 1], - (object) ['body' => 'message2', 'id' => 2], - ]; - - $this->ironmq->expects($this->once())->method('getMessages') - ->with($this->equalTo('send-newsletter'), $this->equalTo(2)) - ->will($this->returnValue($ironmqMessages)); - - $this->assertEquals(['message1', 1], $this->driver->popMessage('send-newsletter')); - $this->assertEquals(['message2', 2], $this->driver->popMessage('send-newsletter')); - } - - public function testItPopMessages() - { - $this->ironmq - ->expects($this->at(0)) - ->method('getMessages') - ->with($this->equalTo('my-queue1'), $this->equalTo(2), $this->equalTo(60)) - ->will($this->returnValue([ - (object) ['body' => 'message1', 'id' => 1], - ])); - $this->ironmq - ->expects($this->at(1)) - ->method('getMessages') - ->with($this->equalTo('my-queue2'), $this->equalTo(2), $this->equalTo(60)) - ->will($this->returnValue([ - (object) ['body' => 'message2', 'id' => 2], - ])); - $this->ironmq - ->expects($this->at(1)) - ->method('getMessages') - ->with($this->equalTo('my-queue2'), $this->equalTo(2), $this->equalTo(60)) - ->will($this->returnValue(null)); - - $this->assertEquals(['message1', 1], $this->driver->popMessage('my-queue1')); - $this->assertEquals(['message2', 2], $this->driver->popMessage('my-queue2')); - $this->assertEquals([null, null], $this->driver->popMessage('my-queue2', 0.01)); - } -} diff --git a/tests/Driver/Pheanstalk/DriverTest.php b/tests/Driver/Pheanstalk/DriverTest.php deleted file mode 100644 index 97f30ff0..00000000 --- a/tests/Driver/Pheanstalk/DriverTest.php +++ /dev/null @@ -1,117 +0,0 @@ -pheanstalk = $this->getMockBuilder(Pheanstalk::class) - ->setMethods([ - 'listTubes', - 'statsTube', - 'putInTube', - 'reserveFromTube', - 'delete', - 'stats', - ]) - ->disableOriginalConstructor() - ->getMock(); - - $this->driver = new Driver($this->pheanstalk); - } - - public function testItExposesInfo() - { - $driver = new Driver($this->pheanstalk); - - $info = new \ArrayObject(['info' => true]); - - $this->pheanstalk->expects($this->once())->method('stats') - ->will($this->returnValue($info)); - - $this->assertEquals(['info' => true], $driver->info()); - } - - public function testItImplementsDriverInterface() - { - $this->assertInstanceOf(\Bernard\Driver::class, $this->driver); - } - - public function testItCountsNumberOfMessagesInQueue() - { - $this->pheanstalk->expects($this->once())->method('statsTube') - ->with($this->equalTo('send-newsletter'))->will($this->returnValue(['current-jobs-ready' => 4])); - - $this->assertEquals(4, $this->driver->countMessages('send-newsletter')); - } - - public function testItListQueues() - { - $queues = [ - 'failed', - 'queue1', - ]; - - $this->pheanstalk->expects($this->once())->method('listTubes') - ->will($this->returnValue($queues)); - - $this->assertEquals($queues, $this->driver->listQueues()); - } - - public function testAcknowledgeMessage() - { - $this->pheanstalk->expects($this->once())->method('delete') - ->with($this->isInstanceOf(Job::class)); - - $this->driver->acknowledgeMessage('my-queue', new Job(1, null)); - } - - public function testItPeeksInAQueue() - { - $this->assertEquals([], $this->driver->peekQueue('my-queue2')); - } - - public function testItPushesMessages() - { - $this->pheanstalk - ->expects($this->once()) - ->method('putInTube') - ->with($this->equalTo('my-queue'), $this->equalTo('This is a message')); - - $this->driver->pushMessage('my-queue', 'This is a message'); - } - - public function testItPopMessages() - { - $this->pheanstalk - ->expects($this->at(0)) - ->method('reserveFromTube') - ->with($this->equalTo('my-queue1'), $this->equalTo(5)) - ->will($this->returnValue($job1 = new Job(1, 'message1'))); - $this->pheanstalk - ->expects($this->at(1)) - ->method('reserveFromTube') - ->with($this->equalTo('my-queue2'), $this->equalTo(5)) - ->will($this->returnValue($job2 = new Job(2, 'message2'))); - $this->pheanstalk - ->expects($this->at(1)) - ->method('reserveFromTube') - ->with($this->equalTo('my-queue2'), $this->equalTo(5)) - ->will($this->returnValue(null)); - - $this->assertEquals(['message1', $job1], $this->driver->popMessage('my-queue1')); - $this->assertEquals(['message2', $job2], $this->driver->popMessage('my-queue2')); - $this->assertEquals([null, null], $this->driver->popMessage('my-queue2')); - } -} diff --git a/tests/Driver/PhpRedis/DriverTest.php b/tests/Driver/PhpRedis/DriverTest.php deleted file mode 100644 index 3b157182..00000000 --- a/tests/Driver/PhpRedis/DriverTest.php +++ /dev/null @@ -1,99 +0,0 @@ -markTestSkipped('"redis" extension is not loaded.'); - } - - $this->redis = $this->getMockBuilder('Redis')->setMethods([ - 'lLen', - 'sMembers', - 'lRange', - 'blPop', - 'sRemove', - 'del', - 'sAdd', - 'sContains', - 'rPush', - 'sRem', - ])->getMock(); - - $this->connection = new Driver($this->redis); - } - - public function testItImplementsDriverInterface() - { - $this->assertInstanceOf(\Bernard\Driver::class, $this->connection); - } - - public function testItCountsNumberOfMessagesInQueue() - { - $this->redis->expects($this->once())->method('lLen')->with($this->equalTo('queue:send-newsletter')) - ->will($this->returnValue(4)); - - $this->assertEquals(4, $this->connection->countMessages('send-newsletter')); - } - - public function testItGetsAllKeys() - { - $this->redis->expects($this->once())->method('sMembers')->with($this->equalTo('queues')) - ->will($this->returnValue(['failed', 'queue1'])); - - $this->assertEquals(['failed', 'queue1'], $this->connection->listQueues()); - } - - public function testItPeeksInAQueue() - { - $this->redis->expects($this->at(0))->method('lRange') - ->with($this->equalTo('queue:my-queue'), $this->equalTo(10), $this->equalTo(19)) - ->will($this->returnValue(['message1'])); - - $this->redis->expects($this->at(1))->method('lRange') - ->with($this->equalTo('queue:send-newsletter'), $this->equalTo(0), $this->equalTo(19)) - ->will($this->returnValue(['message2'])); - - $this->assertEquals(['message1'], $this->connection->peekQueue('my-queue', 10, 10)); - $this->assertEquals(['message2'], $this->connection->peekQueue('send-newsletter')); - } - - public function testItRemovesAQueue() - { - $this->redis->expects($this->once())->method('del')->with($this->equalTo('queue:name')); - $this->redis->expects($this->once())->method('srem')->with($this->equalTo('queues'), $this->equalTo('name')); - - $this->connection->removeQueue('name'); - } - - public function testItCreatesAQueue() - { - $this->redis->expects($this->once())->method('sAdd')->with($this->equalTo('queues'), $this->equalTo('send-newsletter')); - - $this->connection->createQueue('send-newsletter'); - } - - public function testItPushesMessages() - { - $this->redis->expects($this->once())->method('rPush')->with($this->equalTo('queue:send-newsletter'), $this->equalTo('This is a message')); - - $this->connection->pushMessage('send-newsletter', 'This is a message'); - } - - public function testItPopMessages() - { - $this->redis->expects($this->at(0))->method('blPop')->with($this->equalTo(['queue:send-newsletter'])) - ->will($this->returnValue(['my-queue', 'message1'])); - - $this->redis->expects($this->at(1))->method('blPop')->with($this->equalTo(['queue:ask-forgiveness']), $this->equalTo(30)) - ->will($this->returnValue(['my-queue2', 'message2'])); - - $this->assertEquals(['message1', null], $this->connection->popMessage('send-newsletter')); - $this->assertEquals(['message2', null], $this->connection->popMessage('ask-forgiveness', 30)); - } -} diff --git a/tests/Driver/Predis/DriverTest.php b/tests/Driver/Predis/DriverTest.php deleted file mode 100644 index cadf38e2..00000000 --- a/tests/Driver/Predis/DriverTest.php +++ /dev/null @@ -1,41 +0,0 @@ -redis = $this->getMockBuilder(Client::class)->setMethods([ - 'lLen', - 'sMembers', - 'lRange', - 'blPop', - 'sRemove', - 'del', - 'sAdd', - 'sContains', - 'rPush', - 'sRem', - ])->getMock(); - - $this->connection = new Driver($this->redis); - } - - public function testItPopMessages() - { - $this->redis->expects($this->at(0))->method('blPop')->with($this->equalTo('queue:send-newsletter')) - ->will($this->returnValue(['my-queue', 'message1'])); - - $this->redis->expects($this->at(1))->method('blPop')->with($this->equalTo('queue:ask-forgiveness'), $this->equalTo(30)) - ->will($this->returnValue(['my-queue2', 'message2'])); - - $this->assertEquals(['message1', null], $this->connection->popMessage('send-newsletter')); - $this->assertEquals(['message2', null], $this->connection->popMessage('ask-forgiveness', 30)); - } -} diff --git a/tests/Driver/Sqs/DriverTest.php b/tests/Driver/Sqs/DriverTest.php deleted file mode 100644 index 1da2d24f..00000000 --- a/tests/Driver/Sqs/DriverTest.php +++ /dev/null @@ -1,305 +0,0 @@ -sqs = $this->getMockBuilder(SqsClient::class) - ->disableOriginalConstructor() - ->setMethods([ - 'createQueue', - 'deleteQueue', - 'getQueueUrl', - 'getQueueAttributes', - 'listQueues', - 'sendMessage', - 'receiveMessage', - 'deleteMessage', - ]) - ->getMock(); - - $this->driver = new Driver($this->sqs, ['send-newsletter' => 'url']); - } - - public function testItExposesInfo() - { - $driver = new Driver($this->sqs, [], 10); - - $this->assertEquals(['prefetch' => 10], $driver->info()); - $this->assertEquals(['prefetch' => 2], $this->driver->info()); - } - - public function testItImplementsDriverInterface() - { - $this->assertInstanceOf(AbstractPrefetchDriver::class, $this->driver); - } - - public function testItCreatesQueue() - { - $this->sqs - ->expects($this->once()) - ->method('createQueue') - ->with($this->equalTo(['QueueName' => self::DUMMY_QUEUE_NAME])) - ->will($this->returnValue( - $this->wrapResult([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX, - ]) - )); - - // Calling this twice asserts that if queue exists - // there won't be attempt to create it. - $this->driver->createQueue(self::DUMMY_QUEUE_NAME); - $this->driver->createQueue(self::DUMMY_QUEUE_NAME); - } - - public function testItCreatesFifoQueue() - { - $this->sqs - ->expects($this->once()) - ->method('createQueue') - ->with($this->equalTo([ - 'QueueName' => self::DUMMY_FIFO_QUEUE_NAME, - 'Attributes' => [ - 'FifoQueue' => 'true', - ], - ])) - ->will($this->returnValue( - $this->wrapResult([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX, - ]) - )); - - // Calling this twice asserts that if queue exists - // there won't be attempt to create it. - $this->driver->createQueue(self::DUMMY_FIFO_QUEUE_NAME); - $this->driver->createQueue(self::DUMMY_FIFO_QUEUE_NAME); - } - - public function testItDeletesQueue() - { - $this->assertSqsQueueUrl(); - $this->sqs - ->expects($this->once()) - ->method('deleteQueue') - ->with($this->equalTo(['QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/'.self::DUMMY_QUEUE_NAME])); - - $this->driver->removeQueue(self::DUMMY_QUEUE_NAME); - } - - public function testItCountsNumberOfMessagesInQueue() - { - $this->assertSqsQueueUrl(); - $this->sqs - ->expects($this->once()) - ->method('getQueueAttributes') - ->with($this->equalTo([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/'.self::DUMMY_QUEUE_NAME, - 'AttributeNames' => ['ApproximateNumberOfMessages'], - ])) - ->will($this->returnValue( - $this->wrapResult([ - 'Attributes' => ['ApproximateNumberOfMessages' => 4], - ]) - )); - - $this->assertEquals(4, $this->driver->countMessages(self::DUMMY_QUEUE_NAME)); - } - - public function testUnresolveableQueueNameThrowsException() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Queue "unknown" cannot be resolved to an url.'); - - $this->driver->popMessage('unknown'); - } - - public function testItGetsAllQueues() - { - $driver = new Driver($this->sqs, [ - 'import-users' => 'alreadyknowurl/import_users_prod', - ]); - - $this->sqs - ->expects($this->once()) - ->method('listQueues') - ->will($this->returnValue($this->wrapResult([ - 'QueueUrls' => [ - 'https://sqs.eu-west-1.amazonaws.com/123123/failed', - 'https://sqs.eu-west-1.amazonaws.com/123123/queue1', - 'alreadyknowurl/import_users_prod', - ], - ]))); - - $queues = ['import-users', 'failed', 'queue1']; - - $this->assertEquals($queues, $driver->listQueues()); - } - - public function testItPrefetchesMessages() - { - $query = [ - 'QueueUrl' => 'url', - 'MaxNumberOfMessages' => 2, - 'WaitTimeSeconds' => 5, - ]; - - $sqsMessages = $this->wrapResult([ - 'Messages' => [ - ['Body' => 'message0', 'ReceiptHandle' => 'r0'], - ['Body' => 'message1', 'ReceiptHandle' => 'r1'], - ], - ]); - - $this->sqs->expects($this->once())->method('receiveMessage') - ->with($this->equalTo($query))->will($this->returnValue($sqsMessages)); - - $this->assertEquals(['message0', 'r0'], $this->driver->popMessage('send-newsletter')); - $this->assertEquals(['message1', 'r1'], $this->driver->popMessage('send-newsletter')); - } - - public function testItPushesMessages() - { - $message = 'This is a message'; - - $this->assertSqsQueueUrl(); - $this->sqs - ->expects($this->once()) - ->method('sendMessage') - ->with($this->equalTo([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/'.self::DUMMY_QUEUE_NAME, - 'MessageBody' => $message, - ])); - $this->driver->pushMessage(self::DUMMY_QUEUE_NAME, $message); - } - - public function testItPushesMessagesToFifoQueue() - { - $message = 'This is a message'; - - $this->assertSqsFifoQueueUrl(); - $this->sqs - ->expects($this->once()) - ->method('sendMessage') - ->with($this->equalTo([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/'.self::DUMMY_FIFO_QUEUE_NAME, - 'MessageBody' => $message, - 'MessageGroupId' => \Bernard\Driver\Sqs\Driver::class.'::pushMessage', - 'MessageDeduplicationId' => md5($message), - ])); - $this->driver->pushMessage(self::DUMMY_FIFO_QUEUE_NAME, $message); - } - - public function testItPopMessages() - { - $this->sqs - ->expects($this->at(0)) - ->method('getQueueUrl') - ->with($this->equalTo([ - 'QueueName' => self::DUMMY_QUEUE_NAME.'0', - ])) - ->will($this->returnValue($this->wrapResult([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX - .'/'.self::DUMMY_QUEUE_NAME.'0', - ]))); - $this->sqs - ->expects($this->at(1)) - ->method('receiveMessage') - ->with($this->equalTo([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/'.self::DUMMY_QUEUE_NAME.'0', - 'MaxNumberOfMessages' => 2, - 'WaitTimeSeconds' => 5, - ])) - ->will($this->returnValue($this->wrapResult([ - 'Messages' => [ - ['Body' => 'message0', 'ReceiptHandle' => 'r0'], - ], - ]))); - - $this->sqs - ->expects($this->at(2)) - ->method('getQueueUrl') - ->with($this->equalTo([ - 'QueueName' => self::DUMMY_QUEUE_NAME.'1', - ])) - ->will($this->returnValue($this->wrapResult([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/my-queue1', - ]))); - $this->sqs - ->expects($this->at(3)) - ->method('receiveMessage') - ->with($this->equalTo([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX.'/my-queue1', - 'MaxNumberOfMessages' => 2, - 'WaitTimeSeconds' => 30, - ])) - ->will($this->returnValue($this->wrapResult([ - 'Messages' => [ - ['Body' => 'message1', 'ReceiptHandle' => 'r1'], - ], - ]))); - - $this->assertEquals(['message0', 'r0'], $this->driver->popMessage('my-queue0')); - $this->assertEquals(['message1', 'r1'], $this->driver->popMessage('my-queue1', 30)); - $this->assertEquals([null, null], $this->driver->popMessage('send-newsletter')); - } - - public function testAcknowledgeMessage() - { - $this->sqs->expects($this->once())->method('deleteMessage') - ->with($this->equalTo([ - 'QueueUrl' => 'url', - 'ReceiptHandle' => 'r0', - ])); - - $this->driver->acknowledgeMessage('send-newsletter', 'r0'); - } - - private function assertSqsQueueUrl() - { - $this->sqs - ->expects($this->once()) - ->method('getQueueUrl') - ->with($this->equalTo(['QueueName' => self::DUMMY_QUEUE_NAME])) - ->will($this->returnValue($this->wrapResult([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX - .'/'.self::DUMMY_QUEUE_NAME, - ]))); - } - - private function assertSqsFifoQueueUrl() - { - $this->sqs - ->expects($this->once()) - ->method('getQueueUrl') - ->with($this->equalTo(['QueueName' => self::DUMMY_FIFO_QUEUE_NAME])) - ->will($this->returnValue($this->wrapResult([ - 'QueueUrl' => self::DUMMY_QUEUE_URL_PREFIX - .'/'.self::DUMMY_FIFO_QUEUE_NAME, - ]))); - } - - private function wrapResult($data = []) - { - return class_exists('Aws\Common\Aws') - ? new Model($data) - : new Result($data); - } -} From 4e9d0ce82004df807e842ca81dd02b4a35d7fc49 Mon Sep 17 00:00:00 2001 From: alexpozzi Date: Fri, 18 Mar 2022 15:26:48 +0100 Subject: [PATCH 080/108] fix: php 8.1 Countable::count incompatibilities --- src/Queue/RoundRobinQueue.php | 1 + src/QueueFactory/InMemoryFactory.php | 1 + src/QueueFactory/PersistentFactory.php | 1 + 3 files changed, 3 insertions(+) diff --git a/src/Queue/RoundRobinQueue.php b/src/Queue/RoundRobinQueue.php index 4665524a..b9e500ed 100644 --- a/src/Queue/RoundRobinQueue.php +++ b/src/Queue/RoundRobinQueue.php @@ -148,6 +148,7 @@ public function __toString() /** * @return int */ + #[\ReturnTypeWillChange] public function count() { return array_sum(array_map('count', $this->queues)); diff --git a/src/QueueFactory/InMemoryFactory.php b/src/QueueFactory/InMemoryFactory.php index 6f171342..0366ecfd 100644 --- a/src/QueueFactory/InMemoryFactory.php +++ b/src/QueueFactory/InMemoryFactory.php @@ -35,6 +35,7 @@ public function all() /** * {@inheritdoc} */ + #[\ReturnTypeWillChange] public function count() { return count($this->queues); diff --git a/src/QueueFactory/PersistentFactory.php b/src/QueueFactory/PersistentFactory.php index 0ed4ec6a..a5382ffe 100644 --- a/src/QueueFactory/PersistentFactory.php +++ b/src/QueueFactory/PersistentFactory.php @@ -63,6 +63,7 @@ public function exists($queueName) /** * @return int */ + #[\ReturnTypeWillChange] public function count() { return count($this->driver->listQueues()); From 4bf5746ce398e08a2648d1c6b644e59876c8dee3 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Tue, 3 May 2022 23:24:01 +0200 Subject: [PATCH 081/108] refactor!: relocate appengine driver to the drivers package Signed-off-by: Mark Sagi-Kazar --- src/Driver/AppEngine/Driver.php | 105 -------------------------- tests/Driver/AppEngine/DriverTest.php | 58 -------------- tests/Fixtures/PushTask.php | 28 ------- 3 files changed, 191 deletions(-) delete mode 100644 src/Driver/AppEngine/Driver.php delete mode 100644 tests/Driver/AppEngine/DriverTest.php delete mode 100644 tests/Fixtures/PushTask.php diff --git a/src/Driver/AppEngine/Driver.php b/src/Driver/AppEngine/Driver.php deleted file mode 100644 index 89fea9dc..00000000 --- a/src/Driver/AppEngine/Driver.php +++ /dev/null @@ -1,105 +0,0 @@ - 'endpoint') to route messages to the - * correct place. - */ -final class Driver implements \Bernard\Driver -{ - private $queueMap; - - /** - * @param array $queueMap - */ - public function __construct(array $queueMap) - { - $this->queueMap = $queueMap; - } - - /** - * {@inheritdoc} - */ - public function listQueues() - { - return array_flip($this->queueMap); - } - - /** - * {@inheritdoc} - */ - public function createQueue($queueName) - { - } - - /** - * {@inheritdoc} - */ - public function countMessages($queueName) - { - } - - /** - * {@inheritdoc} - */ - public function pushMessage($queueName, $message) - { - $task = new PushTask($this->resolveEndpoint($queueName), compact('message')); - $task->add($queueName); - } - - /** - * {@inheritdoc} - */ - public function popMessage($queueName, $duration = 5) - { - } - - /** - * {@inheritdoc} - */ - public function acknowledgeMessage($queueName, $receipt) - { - } - - /** - * {@inheritdoc} - */ - public function removeQueue($queueName) - { - } - - /** - * {@inheritdoc} - */ - public function peekQueue($queueName, $index = 0, $limit = 20) - { - return []; - } - - /** - * {@inheritdoc} - */ - public function info() - { - return []; - } - - /** - * @param string $queueName - * - * @return string - */ - private function resolveEndpoint($queueName) - { - if (isset($this->queueMap[$queueName])) { - return $this->queueMap[$queueName]; - } - - return '/_ah/queue/'.$queueName; - } -} diff --git a/tests/Driver/AppEngine/DriverTest.php b/tests/Driver/AppEngine/DriverTest.php deleted file mode 100644 index b0964baa..00000000 --- a/tests/Driver/AppEngine/DriverTest.php +++ /dev/null @@ -1,58 +0,0 @@ -driver = new Driver([ - 'send-newsletter' => '/url_endpoint', - ]); - } - - public function tearDown(): void - { - PushTask::$messages = []; - } - - public function testItQueuesPushTask() - { - $this->driver->pushMessage('send-newsletter', 'message'); - - $message = new PushTask('/url_endpoint', ['message' => 'message']); - $this->assertEquals($message, PushTask::$messages['send-newsletter'][0]); - } - - public function testItUsesDefaultEndpointWhenAliasArentThere() - { - $this->driver->pushMessage('import-users', 'message'); - $this->driver->pushMessage('calculate-reports', 'message'); - - $messages = [ - new PushTask('/_ah/queue/import-users', ['message' => 'message']), - new PushTask('/_ah/queue/calculate-reports', ['message' => 'message']), - ]; - - $this->assertEquals($messages[0], PushTask::$messages['import-users'][0]); - $this->assertEquals($messages[1], PushTask::$messages['calculate-reports'][0]); - } - - public function testListQueues() - { - $this->assertEquals(['/url_endpoint' => 'send-newsletter'], $this->driver->listQueues()); - } -} diff --git a/tests/Fixtures/PushTask.php b/tests/Fixtures/PushTask.php deleted file mode 100644 index f9dc8a05..00000000 --- a/tests/Fixtures/PushTask.php +++ /dev/null @@ -1,28 +0,0 @@ -url_path = $url_path; - $this->query_data = $query_data; - $this->options = $options; - } - - public function add($queueName = 'default') - { - static::$messages[$queueName][] = $this; - } -} From 8a4dc62fe06ecb365261cc156fb908c569037daf Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 00:13:37 +0200 Subject: [PATCH 082/108] build: add Nix flake Signed-off-by: Mark Sagi-Kazar --- .editorconfig | 3 +++ .envrc | 6 ++++++ .gitignore | 1 + flake.lock | 42 ++++++++++++++++++++++++++++++++++++++++++ flake.nix | 29 +++++++++++++++++++++++++++++ 5 files changed, 81 insertions(+) create mode 100644 .envrc create mode 100644 flake.lock create mode 100644 flake.nix diff --git a/.editorconfig b/.editorconfig index 677e36e2..847981db 100644 --- a/.editorconfig +++ b/.editorconfig @@ -7,3 +7,6 @@ indent_size = 4 indent_style = space insert_final_newline = true trim_trailing_whitespace = true + +[*.nix] +indent_size = 2 diff --git a/.envrc b/.envrc new file mode 100644 index 00000000..1e62cb13 --- /dev/null +++ b/.envrc @@ -0,0 +1,6 @@ +if ! has nix_direnv_version || ! nix_direnv_version 2.1.0; then + source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/2.1.0/direnvrc" "sha256-FAT2R9yYvVg516v3LiogjIc8YfsbWbMM/itqWsm5xTA=" +fi +use flake + +export PATH="$PWD/$(composer config vendor-dir)/bin:$PATH" diff --git a/.gitignore b/.gitignore index 47d86c7c..c1a7be4a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +/.direnv/ .php_cs .php_cs.cache .phpunit.result.cache diff --git a/flake.lock b/flake.lock new file mode 100644 index 00000000..1146b231 --- /dev/null +++ b/flake.lock @@ -0,0 +1,42 @@ +{ + "nodes": { + "flake-utils": { + "locked": { + "lastModified": 1649676176, + "narHash": "sha256-OWKJratjt2RW151VUlJPRALb7OU2S5s+f0vLj4o1bHM=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "a4b154ebbdc88c8498a5c7b01589addc9e9cb678", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1651558728, + "narHash": "sha256-8HzyRnWlgZluUrVFNOfZAOlA1fghpOSezXvxhalGMUo=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "cbe587c735b734405f56803e267820ee1559e6c1", + "type": "github" + }, + "original": { + "id": "nixpkgs", + "ref": "nixos-unstable", + "type": "indirect" + } + }, + "root": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 00000000..7ca8ad25 --- /dev/null +++ b/flake.nix @@ -0,0 +1,29 @@ +{ + description = "Official Bernard drivers"; + + inputs = { + nixpkgs.url = "nixpkgs/nixos-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + }; + + outputs = { self, nixpkgs, flake-utils, ... }: + flake-utils.lib.eachDefaultSystem ( + system: + let + pkgs = import nixpkgs { inherit system; }; + in + { + devShells.default = pkgs.mkShell { + buildInputs = with pkgs; + [ + git + php + php.packages.composer + php.packages.phpstan + php.packages.php-cs-fixer + # php.packages.psalm + ]; + }; + } + ); +} From 84e84b06b720de20737b2d027463b6d91eea8100 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 00:50:03 +0200 Subject: [PATCH 083/108] chore: update composer.json Signed-off-by: Mark Sagi-Kazar --- composer.json | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/composer.json b/composer.json index 8b6f64b1..f79bb643 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,12 @@ "name": "bernard/bernard", "description": "Message queue abstraction layer", "license": "MIT", - "keywords": ["message queue", "message", "queue", "bernard"], + "keywords": [ + "message queue", + "message", + "queue", + "bernard" + ], "homepage": "https://github.com/bernardphp/bernard", "type": "library", "require": { @@ -11,7 +16,7 @@ "bernard/normalt": "^1.0", "symfony/event-dispatcher": "^3.0 || ^4.0" }, - "require-dev" : { + "require-dev": { "doctrine/dbal": "^2.5", "doctrine/instantiator": "^1.0.5", "friends-of-phpspec/phpspec-code-coverage": "^6.0", @@ -25,13 +30,15 @@ "doctrine/dbal": "Allow sending messages to simulated message queue in a database via doctrine dbal", "mongodb/mongodb": "Allow sending messages to a MongoDB server via PHP Driver" }, - "autoload" : { - "psr-4" : { "Bernard\\" : "src/" } + "autoload": { + "psr-4": { + "Bernard\\": "src/" + } }, - "autoload-dev" : { - "psr-4" : { - "Bernard\\Tests\\" : "tests/", - "spec\\Bernard\\" : "spec/" + "autoload-dev": { + "psr-4": { + "Bernard\\Tests\\": "tests/", + "spec\\Bernard\\": "spec/" } }, "config": { @@ -49,9 +56,9 @@ ], "test-functional": "php vendor/bin/phpunit -v --group functional" }, - "extra" : { - "branch-alias" : { - "dev-master" : "2.0.x-dev" + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" } }, "prefer-stable": true, From dedbcf6a7224093ad32f0d00592fb04060c6370e Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 00:55:14 +0200 Subject: [PATCH 084/108] feat!: drop PHP 7 support Signed-off-by: Mark Sagi-Kazar --- .github/workflows/ci.yaml | 4 ++-- composer.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index f495b48d..bd8d97c6 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -15,7 +15,7 @@ jobs: - name: Set up PHP uses: shivammathur/setup-php@v2 with: - php-version: '7.4' + php-version: '8.0' coverage: none extensions: mbstring, intl tools: composer:v2 @@ -38,7 +38,7 @@ jobs: strategy: max-parallel: 10 matrix: - php: ['7.4', '8.0'] + php: ['8.0', '8.1'] steps: - name: Set up PHP diff --git a/composer.json b/composer.json index f79bb643..b202a9e9 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,7 @@ "homepage": "https://github.com/bernardphp/bernard", "type": "library", "require": { - "php": ">=7.4", + "php": ">=8.0", "beberlei/assert": "^2.1 || ^3.0", "bernard/normalt": "^1.0", "symfony/event-dispatcher": "^3.0 || ^4.0" From 7d0590bfdf47d4faf278a4a266fe34064641aab7 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 00:06:25 +0200 Subject: [PATCH 085/108] feat!: rewrite Driver interface Signed-off-by: Mark Sagi-Kazar --- src/Driver.php | 67 ++++++++++++++++--------------------------- src/DriverMessage.php | 27 +++++++++++++++++ 2 files changed, 51 insertions(+), 43 deletions(-) create mode 100644 src/DriverMessage.php diff --git a/src/Driver.php b/src/Driver.php index b98a0c52..f0f941b6 100644 --- a/src/Driver.php +++ b/src/Driver.php @@ -1,79 +1,60 @@ message = $message; + $this->receipt = $receipt; + } +} From 9c08db91b7ff5e949a23db88d38f34fa51ffa48c Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 00:25:37 +0200 Subject: [PATCH 086/108] refactor!: apply Driver changes to AbstractPrefetchDriver Signed-off-by: Mark Sagi-Kazar --- src/Driver/AbstractPrefetchDriver.php | 14 +++++------ src/Driver/PrefetchMessageCache.php | 30 ++++++++++------------- tests/Driver/PrefetchMessageCacheTest.php | 6 +++-- 3 files changed, 24 insertions(+), 26 deletions(-) diff --git a/src/Driver/AbstractPrefetchDriver.php b/src/Driver/AbstractPrefetchDriver.php index ec97fd8a..74209c21 100644 --- a/src/Driver/AbstractPrefetchDriver.php +++ b/src/Driver/AbstractPrefetchDriver.php @@ -1,5 +1,7 @@ prefetch = $prefetch ? (int) $prefetch : 2; + $this->prefetch = $prefetch ?? 2; $this->cache = new PrefetchMessageCache(); } } diff --git a/src/Driver/PrefetchMessageCache.php b/src/Driver/PrefetchMessageCache.php index fa2d6c69..84727fca 100644 --- a/src/Driver/PrefetchMessageCache.php +++ b/src/Driver/PrefetchMessageCache.php @@ -1,18 +1,20 @@ get($queueName); $cache->enqueue($message); @@ -21,28 +23,22 @@ public function push($queueName, array $message) /** * Get the next message in line. Or nothing if there is no more * in the cache. - * - * @param string $queueName - * - * @return array|null */ - public function pop($queueName) + public function pop(string $queueName): ?\Bernard\DriverMessage { $cache = $this->get($queueName); if (!$cache->isEmpty()) { return $cache->dequeue(); } + + return null; } /** * Create the queue cache internally if it doesn't yet exists. - * - * @param string $queueName - * - * @return \SplQueue */ - protected function get($queueName) + private function get(string $queueName): \SplQueue { if (isset($this->caches[$queueName])) { return $this->caches[$queueName]; diff --git a/tests/Driver/PrefetchMessageCacheTest.php b/tests/Driver/PrefetchMessageCacheTest.php index 5eab0d51..d14b8c54 100644 --- a/tests/Driver/PrefetchMessageCacheTest.php +++ b/tests/Driver/PrefetchMessageCacheTest.php @@ -8,10 +8,12 @@ class PrefetchMessageCacheTest extends \PHPUnit\Framework\TestCase { public function testPushesAndPop() { + $driverMessage = new \Bernard\DriverMessage('message1', 'r0'); + $cache = new PrefetchMessageCache(); - $cache->push('my-queue', ['message1', 'r0']); + $cache->push('my-queue', $driverMessage); - $this->assertEquals(['message1', 'r0'], $cache->pop('my-queue')); + $this->assertEquals($driverMessage, $cache->pop('my-queue')); $this->assertNull($cache->pop('my-queue')); } } From e2ca5ad61e56ec97d5db5c77718a7d687a986c5f Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 00:36:44 +0200 Subject: [PATCH 087/108] refactor!: apply Driver changes to Doctrine Signed-off-by: Mark Sagi-Kazar --- src/Driver/Doctrine/Driver.php | 118 ++++++++++++--------------------- 1 file changed, 41 insertions(+), 77 deletions(-) diff --git a/src/Driver/Doctrine/Driver.php b/src/Driver/Doctrine/Driver.php index 415e91b9..c418b545 100644 --- a/src/Driver/Doctrine/Driver.php +++ b/src/Driver/Doctrine/Driver.php @@ -1,28 +1,21 @@ connection = $connection; } - /** - * {@inheritdoc} - */ - public function listQueues() + public function listQueues(): array { $statement = $this->connection->prepare('SELECT name FROM bernard_queues'); $statement->execute(); @@ -30,10 +23,7 @@ public function listQueues() return $statement->fetchAll(\PDO::FETCH_COLUMN); } - /** - * {@inheritdoc} - */ - public function createQueue($queueName) + public function createQueue(string $queueName): void { try { $this->connection->insert('bernard_queues', ['name' => $queueName]); @@ -43,23 +33,13 @@ public function createQueue($queueName) } } - /** - * {@inheritdoc} - */ - public function countMessages($queueName) + public function removeQueue(string $queueName): void { - $query = 'SELECT COUNT(id) FROM bernard_messages WHERE queue = :queue AND visible = :visible'; - - return (int) $this->connection->fetchColumn($query, [ - 'queue' => $queueName, - 'visible' => true, - ]); + $this->connection->delete('bernard_messages', ['queue' => $queueName]); + $this->connection->delete('bernard_queues', ['name' => $queueName]); } - /** - * {@inheritdoc} - */ - public function pushMessage($queueName, $message) + public function pushMessage(string $queueName, string $message): void { $types = ['string', 'string', 'datetime']; $data = [ @@ -72,10 +52,7 @@ public function pushMessage($queueName, $message) $this->connection->insert('bernard_messages', $data, $types); } - /** - * {@inheritdoc} - */ - public function popMessage($queueName, $duration = 5) + public function popMessage(string $queueName, int $duration = 5): ?\Bernard\DriverMessage { $runtime = microtime(true) + $duration; @@ -94,49 +71,38 @@ public function popMessage($queueName, $duration = 5) return $message; } - //sleep for 10 ms + // sleep for 10 ms usleep(10000); } } /** - * {@inheritdoc} + * Execute the actual query and process the response. */ - public function acknowledgeMessage($queueName, $receipt) + private function doPopMessage(string $queueName): ?\Bernard\DriverMessage { - $this->connection->delete('bernard_messages', ['id' => $receipt, 'queue' => $queueName]); - } + $query = 'SELECT id, message FROM bernard_messages + WHERE queue = :queue AND visible = :visible + ORDER BY sentAt LIMIT 1 '.$this->connection->getDatabasePlatform()->getForUpdateSql(); - /** - * {@inheritdoc} - */ - public function peekQueue($queueName, $index = 0, $limit = 20) - { - $parameters = [$queueName, true, $limit, $index]; - $types = ['string', 'boolean', 'integer', 'integer']; + [$id, $message] = $this->connection->fetchArray($query, [ + 'queue' => $queueName, + 'visible' => true, + ]); - $query = 'SELECT message FROM bernard_messages WHERE queue = ? AND visible = ? ORDER BY sentAt LIMIT ? OFFSET ?'; + if ($id) { + $this->connection->update('bernard_messages', ['visible' => 0], compact('id')); - return $this - ->connection - ->executeQuery($query, $parameters, $types) - ->fetchAll(\PDO::FETCH_COLUMN) - ; + return new \Bernard\DriverMessage($message, $id); + } } - /** - * {@inheritdoc} - */ - public function removeQueue($queueName) + public function acknowledgeMessage(string $queueName, mixed $receipt): void { - $this->connection->delete('bernard_messages', ['queue' => $queueName]); - $this->connection->delete('bernard_queues', ['name' => $queueName]); + $this->connection->delete('bernard_messages', ['id' => $receipt, 'queue' => $queueName]); } - /** - * {@inheritdoc} - */ - public function info() + public function info(): array { $params = $this->connection->getParams(); @@ -145,28 +111,26 @@ public function info() return $params; } - /** - * Execute the actual query and process the response. - * - * @param string $queueName - * - * @return array|null - */ - private function doPopMessage($queueName) + public function countMessages(string $queueName): int { - $query = 'SELECT id, message FROM bernard_messages - WHERE queue = :queue AND visible = :visible - ORDER BY sentAt LIMIT 1 '.$this->connection->getDatabasePlatform()->getForUpdateSql(); + $query = 'SELECT COUNT(id) FROM bernard_messages WHERE queue = :queue AND visible = :visible'; - list($id, $message) = $this->connection->fetchArray($query, [ + return (int) $this->connection->fetchColumn($query, [ 'queue' => $queueName, 'visible' => true, ]); + } - if ($id) { - $this->connection->update('bernard_messages', ['visible' => 0], compact('id')); + public function peekQueue(string $queueName, int $index = 0, int $limit = 20): array + { + $parameters = [$queueName, true, $limit, $index]; + $types = ['string', 'boolean', 'integer', 'integer']; - return [$message, $id]; - } + $query = 'SELECT message FROM bernard_messages WHERE queue = ? AND visible = ? ORDER BY sentAt LIMIT ? OFFSET ?'; + + return $this + ->connection + ->executeQuery($query, $parameters, $types) + ->fetchAll(\PDO::FETCH_COLUMN); } } From 715d130ae1e9210bd953cbd726362da5ee732cac Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 00:45:37 +0200 Subject: [PATCH 088/108] refactor!: apply Driver changes to FlatFile Signed-off-by: Mark Sagi-Kazar --- src/Driver/FlatFile/Driver.php | 171 ++++++------------ .../InsufficientPermissionsException.php | 2 + tests/Driver/FlatFile/DriverTest.php | 38 ++-- 3 files changed, 81 insertions(+), 130 deletions(-) diff --git a/src/Driver/FlatFile/Driver.php b/src/Driver/FlatFile/Driver.php index afd91e0c..6e94b79f 100644 --- a/src/Driver/FlatFile/Driver.php +++ b/src/Driver/FlatFile/Driver.php @@ -1,5 +1,7 @@ */ -class Driver implements \Bernard\Driver +final class Driver implements \Bernard\Driver { - private $baseDirectory; + private string $baseDirectory; - private $permissions; + private int $permissions; - /** - * @param string $baseDirectory The base directory - * @param int $permissions permissions to create the file with - */ - public function __construct($baseDirectory, $permissions = 0740) + public function __construct(string $baseDirectory, int $permissions = 0740) { $this->baseDirectory = $baseDirectory; $this->permissions = $permissions; } - /** - * {@inheritdoc} - */ - public function listQueues() + public function listQueues(): array { $it = new \FilesystemIterator($this->baseDirectory, \FilesystemIterator::SKIP_DOTS); @@ -38,16 +33,13 @@ public function listQueues() continue; } - array_push($queues, $file->getBasename()); + $queues[] = $file->getBasename(); } return $queues; } - /** - * {@inheritdoc} - */ - public function createQueue($queueName) + public function createQueue(string $queueName): void { $queueDir = $this->getQueueDirectory($queueName); @@ -58,38 +50,34 @@ public function createQueue($queueName) mkdir($queueDir, 0755, true); } - /** - * {@inheritdoc} - */ - public function countMessages($queueName) + public function removeQueue(string $queueName): void { $iterator = new \RecursiveDirectoryIterator( $this->getQueueDirectory($queueName), \FilesystemIterator::SKIP_DOTS ); $iterator = new \RecursiveIteratorIterator($iterator); - $iterator = new \RegexIterator($iterator, '#\.job$#'); + $iterator = new \RegexIterator($iterator, '#\.job(.proceed)?$#'); - return iterator_count($iterator); + foreach ($iterator as $file) { + /* @var $file \DirectoryIterator */ + unlink($file->getRealPath()); + } + + rmdir($this->getQueueDirectory($queueName)); } - /** - * {@inheritdoc} - */ - public function pushMessage($queueName, $message) + public function pushMessage(string $queueName, string $message): void { $queueDir = $this->getQueueDirectory($queueName); $filename = $this->getJobFilename($queueName); - file_put_contents($queueDir.DIRECTORY_SEPARATOR.$filename, $message); - chmod($queueDir.DIRECTORY_SEPARATOR.$filename, $this->permissions); + file_put_contents($queueDir.\DIRECTORY_SEPARATOR.$filename, $message); + chmod($queueDir.\DIRECTORY_SEPARATOR.$filename, $this->permissions); } - /** - * {@inheritdoc} - */ - public function popMessage($queueName, $duration = 5) + public function popMessage(string $queueName, int $duration = 5): ?\Bernard\DriverMessage { $runtime = microtime(true) + $duration; $queueDir = $this->getQueueDirectory($queueName); @@ -99,8 +87,8 @@ public function popMessage($queueName, $duration = 5) while (microtime(true) < $runtime) { if ($files) { $id = array_pop($files); - if (@rename($queueDir.DIRECTORY_SEPARATOR.$id, $queueDir.DIRECTORY_SEPARATOR.$id.'.proceed')) { - return [file_get_contents($queueDir.DIRECTORY_SEPARATOR.$id.'.proceed'), $id]; + if (@rename($queueDir.\DIRECTORY_SEPARATOR.$id, $queueDir.\DIRECTORY_SEPARATOR.$id.'.proceed')) { + return new \Bernard\DriverMessage(file_get_contents($queueDir.\DIRECTORY_SEPARATOR.$id.'.proceed'), $id); } return $this->processFileOrFail($queueDir, $id); @@ -111,34 +99,24 @@ public function popMessage($queueName, $duration = 5) usleep(1000); } - - return [null, null]; } - /** - * @param string $queueDir - * @param string $id - * - * @return array - */ - private function processFileOrFail($queueDir, $id) { - $name = $queueDir.DIRECTORY_SEPARATOR.$id; + private function processFileOrFail(string $queueDir, string $id): \Bernard\DriverMessage + { + $name = $queueDir.\DIRECTORY_SEPARATOR.$id; $newName = $name.'.proceed'; if (!@rename($name, $newName)) { throw new InsufficientPermissionsException('Unable to process file: '.$name); } - return [file_get_contents($newName), $id]; + return new \Bernard\DriverMessage(file_get_contents($newName), $id); } - /** - * {@inheritdoc} - */ - public function acknowledgeMessage($queueName, $receipt) + public function acknowledgeMessage(string $queueName, mixed $receipt): void { $queueDir = $this->getQueueDirectory($queueName); - $path = $queueDir.DIRECTORY_SEPARATOR.$receipt.'.proceed'; + $path = $queueDir.\DIRECTORY_SEPARATOR.$receipt.'.proceed'; if (!is_file($path)) { return; @@ -147,76 +125,50 @@ public function acknowledgeMessage($queueName, $receipt) unlink($path); } - /** - * {@inheritdoc} - */ - public function peekQueue($queueName, $index = 0, $limit = 20) + public function info(): array + { + return []; + } + + public function countMessages(string $queueName): int + { + $iterator = new \RecursiveDirectoryIterator( + $this->getQueueDirectory($queueName), + \FilesystemIterator::SKIP_DOTS + ); + $iterator = new \RecursiveIteratorIterator($iterator); + $iterator = new \RegexIterator($iterator, '#\.job$#'); + + return iterator_count($iterator); + } + + public function peekQueue(string $queueName, int $index = 0, int $limit = 20): array { $queueDir = $this->getQueueDirectory($queueName); - $it = new \GlobIterator($queueDir.DIRECTORY_SEPARATOR.'*.job', \FilesystemIterator::KEY_AS_FILENAME); + $it = new \GlobIterator($queueDir.\DIRECTORY_SEPARATOR.'*.job', \FilesystemIterator::KEY_AS_FILENAME); $files = array_keys(iterator_to_array($it)); natsort($files); $files = array_reverse($files); - $files = array_slice($files, $index, $limit); + $files = \array_slice($files, $index, $limit); $messages = []; foreach ($files as $file) { - array_push($messages, file_get_contents($queueDir.DIRECTORY_SEPARATOR.$file)); + $messages[] = file_get_contents($queueDir.\DIRECTORY_SEPARATOR.$file); } return $messages; } - /** - * {@inheritdoc} - */ - public function removeQueue($queueName) - { - $iterator = new \RecursiveDirectoryIterator( - $this->getQueueDirectory($queueName), - \FilesystemIterator::SKIP_DOTS - ); - $iterator = new \RecursiveIteratorIterator($iterator); - $iterator = new \RegexIterator($iterator, '#\.job(.proceed)?$#'); - - foreach ($iterator as $file) { - /* @var $file \DirectoryIterator */ - unlink($file->getRealPath()); - } - - rmdir($this->getQueueDirectory($queueName)); - } - - /** - * {@inheritdoc} - */ - public function info() - { - return []; - } - - /** - * @param string $queueName - * - * @return string - */ - private function getQueueDirectory($queueName) + private function getQueueDirectory(string $queueName): string { - return $this->baseDirectory.DIRECTORY_SEPARATOR.str_replace(['\\', '.'], '-', $queueName); + return $this->baseDirectory.\DIRECTORY_SEPARATOR.str_replace(['\\', '.'], '-', $queueName); } - /** - * Generates a uuid. - * - * @param string $queueName - * - * @return string - */ - private function getJobFilename($queueName) + private function getJobFilename(string $queueName): string { $path = $this->baseDirectory.'/bernard.meta'; @@ -226,11 +178,11 @@ private function getJobFilename($queueName) } $file = new \SplFileObject($path, 'r+'); - $file->flock(LOCK_EX); + $file->flock(\LOCK_EX); $meta = unserialize($file->fgets()); - $id = isset($meta[$queueName]) ? $meta[$queueName] : 0; + $id = $meta[$queueName] ?? 0; ++$id; $filename = sprintf('%d.job', $id); @@ -239,21 +191,16 @@ private function getJobFilename($queueName) $content = serialize($meta); $file->fseek(0); - $file->fwrite($content, strlen($content)); - $file->flock(LOCK_UN); + $file->fwrite($content, \strlen($content)); + $file->flock(\LOCK_UN); return $filename; } - /** - * @param string $queueName - * - * @return string[] - */ - private function getJobFiles($queueName) + private function getJobFiles(string $queueName): array { $it = new \GlobIterator( - $this->getQueueDirectory($queueName) . DIRECTORY_SEPARATOR . '*.job', + $this->getQueueDirectory($queueName).\DIRECTORY_SEPARATOR.'*.job', \FilesystemIterator::KEY_AS_FILENAME ); $files = array_keys(iterator_to_array($it)); diff --git a/src/Driver/FlatFile/InsufficientPermissionsException.php b/src/Driver/FlatFile/InsufficientPermissionsException.php index 20c5d19c..d8d6fcfc 100644 --- a/src/Driver/FlatFile/InsufficientPermissionsException.php +++ b/src/Driver/FlatFile/InsufficientPermissionsException.php @@ -1,5 +1,7 @@ driver->createQueue('send-newsletter'); $this->driver->createQueue('send-newsletter'); @@ -42,7 +44,7 @@ public function testCreate() $this->assertDirectoryExists($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'); } - public function testRemove() + public function testRemove(): void { $this->driver->createQueue('send-newsletter'); $this->driver->pushMessage('send-newsletter', 'test'); @@ -52,7 +54,7 @@ public function testRemove() $this->assertDirectoryNotExists($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'); } - public function testRemoveQueueWithPoppedMessage() + public function testRemoveQueueWithPoppedMessage(): void { $this->driver->createQueue('send-newsletter'); $this->driver->pushMessage('send-newsletter', 'test'); @@ -63,7 +65,7 @@ public function testRemoveQueueWithPoppedMessage() $this->assertDirectoryNotExists($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'); } - public function testPushMessage() + public function testPushMessage(): void { $this->driver->createQueue('send-newsletter'); $this->driver->pushMessage('send-newsletter', 'test'); @@ -71,14 +73,14 @@ public function testPushMessage() $this->assertCount(1, glob($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'.\DIRECTORY_SEPARATOR.'*.job')); } - public function testPushMessagePermissions() + public function testPushMessagePermissions(): void { $this->driver = new Driver($this->baseDir, 0770); $this->testPushMessage(); $this->assertEquals('0770', substr(sprintf('%o', fileperms($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'.\DIRECTORY_SEPARATOR.'1.job')), -4)); } - public function testPopMessage() + public function testPopMessage(): void { $this->driver->createQueue('send-newsletter'); @@ -87,19 +89,19 @@ public function testPopMessage() $this->driver->pushMessage('send-newsletter', 'job #3'); foreach (range(3, 1) as $i) { - list($message) = $this->driver->popMessage('send-newsletter'); - $this->assertEquals('job #'.$i, $message); + $driverMessage = $this->driver->popMessage('send-newsletter'); + $this->assertEquals('job #'.$i, $driverMessage->message); } } - public function testPopMessageWhichPushedAfterTheInitialCollect() + public function testPopMessageWhichPushedAfterTheInitialCollect(): void { $this->driver->createQueue('send-newsletter'); - $pid = \pcntl_fork(); + $pid = pcntl_fork(); if ($pid === -1) { - $this->fail('Failed to fork the currently running process: ' . pcntl_strerror(pcntl_get_last_error())); + $this->fail('Failed to fork the currently running process: '.pcntl_strerror(pcntl_get_last_error())); } elseif ($pid === 0) { // Child process pushes a message after the initial collect sleep(5); @@ -107,26 +109,26 @@ public function testPopMessageWhichPushedAfterTheInitialCollect() exit; } - list($message, ) = $this->driver->popMessage('send-newsletter', 10); - $this->assertSame('test', $message); + $driverMessage = $this->driver->popMessage('send-newsletter', 10); + $this->assertSame('test', $driverMessage->message); pcntl_waitpid($pid, $status); } - public function testAcknowledgeMessage() + public function testAcknowledgeMessage(): void { $this->driver->createQueue('send-newsletter'); $this->driver->pushMessage('send-newsletter', 'job #1'); - $message = $this->driver->popMessage('send-newsletter'); + $driverMessage = $this->driver->popMessage('send-newsletter'); - $this->driver->acknowledgeMessage('send-newsletter', $message[1]); + $this->driver->acknowledgeMessage('send-newsletter', $driverMessage->receipt); $this->assertCount(0, glob($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'.\DIRECTORY_SEPARATOR.'*.job')); } - public function testPeekQueue() + public function testPeekQueue(): void { $this->driver->createQueue('send-newsletter'); @@ -139,7 +141,7 @@ public function testPeekQueue() $this->assertCount(10, glob($this->baseDir.\DIRECTORY_SEPARATOR.'send-newsletter'.\DIRECTORY_SEPARATOR.'*.job')); } - public function testListQueues() + public function testListQueues(): void { $this->driver->createQueue('send-newsletter-1'); From 9db0076b3d93dd3c0fe299bcaca2a864ca4edf04 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 09:59:54 +0200 Subject: [PATCH 089/108] refactor!: apply Driver changes to InMemory Signed-off-by: Mark Sagi-Kazar --- src/Driver/InMemory/Driver.php | 81 ++++++++++++---------------------- 1 file changed, 27 insertions(+), 54 deletions(-) diff --git a/src/Driver/InMemory/Driver.php b/src/Driver/InMemory/Driver.php index 8c7af5f6..6683cc26 100644 --- a/src/Driver/InMemory/Driver.php +++ b/src/Driver/InMemory/Driver.php @@ -1,101 +1,74 @@ */ final class Driver implements \Bernard\Driver { - private $queues = []; + private array $queues = []; - /** - * {@inheritdoc} - */ - public function listQueues() + public function listQueues(): array { return array_keys($this->queues); } - /** - * {@inheritdoc} - */ - public function createQueue($queueName) + public function createQueue(string $queueName): void { - if (!array_key_exists($queueName, $this->queues)) { + if (!\array_key_exists($queueName, $this->queues)) { $this->queues[$queueName] = []; } } - /** - * {@inheritdoc} - */ - public function countMessages($queueName) + public function removeQueue(string $queueName): void { - if (array_key_exists($queueName, $this->queues)) { - return count($this->queues[$queueName]); + if (\array_key_exists($queueName, $this->queues)) { + unset($this->queues[$queueName]); } - - return 0; } - /** - * {@inheritdoc} - */ - public function pushMessage($queueName, $message) + public function pushMessage(string $queueName, string $message): void { $this->queues[$queueName][] = $message; } - /** - * {@inheritdoc} - */ - public function popMessage($queueName, $duration = 5) + public function popMessage(string $queueName, int $duration = 5): ?\Bernard\DriverMessage { - if (!array_key_exists($queueName, $this->queues) || count($this->queues[$queueName]) < 1) { - return [null, null]; + if (!\array_key_exists($queueName, $this->queues) || \count($this->queues[$queueName]) < 1) { + return null; } - return [array_shift($this->queues[$queueName]), null]; + return new \Bernard\DriverMessage(array_shift($this->queues[$queueName])); } - /** - * {@inheritdoc} - */ - public function acknowledgeMessage($queueName, $receipt) + public function acknowledgeMessage(string $queueName, mixed $receipt): void { // Noop } - /** - * {@inheritdoc} - */ - public function peekQueue($queueName, $index = 0, $limit = 20) + public function info(): array { - if (array_key_exists($queueName, $this->queues)) { - return array_slice($this->queues[$queueName], $index, $limit); - } - - return null; + return []; } - /** - * {@inheritdoc} - */ - public function removeQueue($queueName) + public function countMessages(string $queueName): int { - if (array_key_exists($queueName, $this->queues)) { - unset($this->queues[$queueName]); + if (\array_key_exists($queueName, $this->queues)) { + return \count($this->queues[$queueName]); } + + return 0; } - /** - * {@inheritdoc} - */ - public function info() + public function peekQueue(string $queueName, int $index = 0, int $limit = 20): array { + if (\array_key_exists($queueName, $this->queues)) { + return \array_slice($this->queues[$queueName], $index, $limit); + } + return []; } } From ac06b8348faa1f5e0b8fa4448aa3bc86aa727c9f Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 10:11:39 +0200 Subject: [PATCH 090/108] refactor!: apply Driver changes to MongoDB Signed-off-by: Mark Sagi-Kazar --- src/Driver/MongoDB/Driver.php | 114 ++++++++++++---------------------- 1 file changed, 40 insertions(+), 74 deletions(-) diff --git a/src/Driver/MongoDB/Driver.php b/src/Driver/MongoDB/Driver.php index 80406efb..ba482f58 100644 --- a/src/Driver/MongoDB/Driver.php +++ b/src/Driver/MongoDB/Driver.php @@ -1,66 +1,48 @@ queues = $queues; $this->messages = $messages; } - /** - * {@inheritdoc} - */ - public function listQueues() + public function listQueues(): array { return $this->queues->distinct('_id'); } - /** - * {@inheritdoc} - */ - public function createQueue($queueName) + public function createQueue(string $queueName): void { - $data = ['_id' => (string) $queueName]; + $data = ['_id' => $queueName]; $this->queues->update($data, $data, ['upsert' => true]); } - /** - * {@inheritdoc} - */ - public function countMessages($queueName) + public function removeQueue(string $queueName): void { - return $this->messages->count([ - 'queue' => (string) $queueName, - 'visible' => true, - ]); + $this->queues->remove(['_id' => $queueName]); + $this->messages->remove(['queue' => $queueName]); } - /** - * {@inheritdoc} - */ - public function pushMessage($queueName, $message) + public function pushMessage(string $queueName, string $message): void { $data = [ - 'queue' => (string) $queueName, - 'message' => (string) $message, + 'queue' => $queueName, + 'message' => $message, 'sentAt' => new MongoDate(), 'visible' => true, ]; @@ -68,81 +50,65 @@ public function pushMessage($queueName, $message) $this->messages->insert($data); } - /** - * {@inheritdoc} - */ - public function popMessage($queueName, $duration = 5) + public function popMessage(string $queueName, int $duration = 5): ?\Bernard\DriverMessage { $runtime = microtime(true) + $duration; while (microtime(true) < $runtime) { $result = $this->messages->findAndModify( - ['queue' => (string) $queueName, 'visible' => true], + ['queue' => $queueName, 'visible' => true], ['$set' => ['visible' => false]], ['message' => 1], ['sort' => ['sentAt' => 1]] ); if ($result) { - return [(string) $result['message'], (string) $result['_id']]; + return new \Bernard\DriverMessage((string) $result['message'], (string) $result['_id']); } usleep(10000); } - return [null, null]; + return null; } - /** - * {@inheritdoc} - */ - public function acknowledgeMessage($queueName, $receipt) + public function acknowledgeMessage(string $queueName, mixed $receipt): void { $this->messages->remove([ '_id' => new MongoId((string) $receipt), - 'queue' => (string) $queueName, + 'queue' => $queueName, + ]); + } + + public function info(): array + { + return [ + 'queues' => (string) $this->queues, + 'messages' => (string) $this->messages, + ]; + } + + public function countMessages(string $queueName): int + { + return $this->messages->count([ + 'queue' => $queueName, + 'visible' => true, ]); } - /** - * {@inheritdoc} - */ - public function peekQueue($queueName, $index = 0, $limit = 20) + public function peekQueue(string $queueName, int $index = 0, int $limit = 20): array { - $query = ['queue' => (string) $queueName, 'visible' => true]; + $query = ['queue' => $queueName, 'visible' => true]; $fields = ['_id' => 0, 'message' => 1]; $cursor = $this->messages ->find($query, $fields) ->sort(['sentAt' => 1]) ->limit($limit) - ->skip($index) - ; + ->skip($index); - $mapper = function ($result) { - return (string) $result['message']; - }; + $mapper = fn ($result) => (string) $result['message']; return array_map($mapper, iterator_to_array($cursor, false)); } - - /** - * {@inheritdoc} - */ - public function removeQueue($queueName) - { - $this->queues->remove(['_id' => $queueName]); - $this->messages->remove(['queue' => (string) $queueName]); - } - - /** - * {@inheritdoc} - */ - public function info() - { - return [ - 'messages' => (string) $this->messages, - 'queues' => (string) $this->queues, - ]; - } } From 9b824f43f12d03c3fe8b921c81ab2ff0596f484f Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 10:36:25 +0200 Subject: [PATCH 091/108] refactor!: apply Driver changes to PersistentQueue Signed-off-by: Mark Sagi-Kazar --- src/Queue/PersistentQueue.php | 8 ++++---- tests/Queue/PersistentQueueTest.php | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Queue/PersistentQueue.php b/src/Queue/PersistentQueue.php index 100ee40f..af1680e4 100644 --- a/src/Queue/PersistentQueue.php +++ b/src/Queue/PersistentQueue.php @@ -91,12 +91,12 @@ public function dequeue($duration = 5) { $this->errorIfClosed(); - list($serialized, $receipt) = $this->driver->popMessage($this->name, $duration); + $driverMessage = $this->driver->popMessage($this->name, $duration); - if ($serialized) { - $envelope = $this->serializer->unserialize($serialized); + if ($driverMessage) { + $envelope = $this->serializer->unserialize($driverMessage->message); - $this->receipts->attach($envelope, $receipt); + $this->receipts->attach($envelope, $driverMessage->receipt); return $envelope; } diff --git a/tests/Queue/PersistentQueueTest.php b/tests/Queue/PersistentQueueTest.php index 6b47796a..792817d4 100644 --- a/tests/Queue/PersistentQueueTest.php +++ b/tests/Queue/PersistentQueueTest.php @@ -34,7 +34,7 @@ public function testAcknowledge() ->with($this->equalTo('send-newsletter'), $this->equalTo('receipt')); $this->driver->expects($this->once())->method('popMessage')->with($this->equalTo('send-newsletter')) - ->will($this->returnValue(['message', 'receipt'])); + ->will($this->returnValue(new \Bernard\DriverMessage('message', 'receipt'))); $this->serializer->expects($this->once())->method('unserialize') ->will($this->returnValue($envelope)); @@ -69,7 +69,7 @@ public function testDequeue() $messageWrapper = new Envelope($this->createMock('Bernard\Message')); $this->driver->expects($this->at(1))->method('popMessage')->with($this->equalTo('send-newsletter')) - ->will($this->returnValue(['serialized', null])); + ->will($this->returnValue(new \Bernard\DriverMessage('serialized', null))); $this->driver->expects($this->at(2))->method('popMessage')->with($this->equalTo('send-newsletter')) ->will($this->returnValue(null)); From 75f9868d8c2753611f14d97516e9f5fe13a6e078 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 12:51:33 +0200 Subject: [PATCH 092/108] chore: add php-cs-fixer config Signed-off-by: Mark Sagi-Kazar --- .gitignore | 4 ++-- .php-cs-fixer.dist.php | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 .php-cs-fixer.dist.php diff --git a/.gitignore b/.gitignore index c1a7be4a..64617b8b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ /.direnv/ -.php_cs -.php_cs.cache +.php-cs-fixer.php +.php-cs-fixer.cache .phpunit.result.cache /_build/ /build/ diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 00000000..7aeb6849 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,21 @@ +setRiskyAllowed(true) + ->setRules([ + '@PSR2' => true, + '@PHP80Migration' => true, + '@PHP80Migration:risky' => true, + '@PHPUnit84Migration:risky' => true, + '@Symfony' => true, + '@Symfony:risky' => true, + 'yoda_style' => false, + ]) + ->setFinder( + PhpCsFixer\Finder::create() + ->in(__DIR__ . '/src') + ->in(__DIR__ . '/tests') + ->name('*.php') + ); + +return $config; From 877822d2a983de7a6bb50c781a9249457b7bcef8 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 12:51:44 +0200 Subject: [PATCH 093/108] chore: run php cs fixer Signed-off-by: Mark Sagi-Kazar --- src/BernardEvents.php | 12 +++-- src/Command/ConsumeCommand.php | 16 +++--- src/Command/ProduceCommand.php | 13 +++-- src/Consumer.php | 50 ++++++------------ .../Doctrine/Command/AbstractCommand.php | 17 +++--- src/Driver/Doctrine/Command/CreateCommand.php | 4 +- src/Driver/Doctrine/Command/DropCommand.php | 4 +- src/Driver/Doctrine/Command/UpdateCommand.php | 4 +- src/Driver/Doctrine/ConnectionListener.php | 8 +-- src/Driver/Doctrine/MessagesSchema.php | 14 ++--- src/Driver/PrefetchMessageCache.php | 4 +- src/Envelope.php | 7 ++- src/Event/EnvelopeEvent.php | 6 +-- src/Event/PingEvent.php | 5 +- src/Event/RejectEnvelopeEvent.php | 4 +- src/EventListener/ErrorLogSubscriber.php | 18 +++---- src/EventListener/FailureSubscriber.php | 10 ++-- src/EventListener/LoggerSubscriber.php | 20 ++----- src/Exception.php | 2 + src/Exception/InvalidOperationException.php | 4 +- src/Exception/NotImplementedException.php | 2 + src/Exception/ReceiverNotFoundException.php | 2 + src/Exception/ServiceUnavailableException.php | 2 + src/Message.php | 2 + src/Message/HasName.php | 4 +- src/Message/HasQueue.php | 2 + src/Message/PlainMessage.php | 13 ++--- src/Normalizer/EnvelopeNormalizer.php | 16 +++--- src/Normalizer/PlainMessageNormalizer.php | 4 +- src/Producer.php | 11 ++-- src/Queue.php | 7 +-- src/Queue/AbstractQueue.php | 8 +-- src/Queue/InMemoryQueue.php | 6 ++- src/Queue/PersistentQueue.php | 14 ++--- src/Queue/RoundRobinQueue.php | 31 +++++------ src/QueueFactory.php | 2 + src/QueueFactory/InMemoryFactory.php | 6 ++- src/QueueFactory/PersistentFactory.php | 12 ++--- src/Receiver.php | 4 +- src/Receiver/CallableReceiver.php | 6 ++- src/Router.php | 4 +- src/Router/ClassNameRouter.php | 2 + src/Router/ContainerReceiverResolver.php | 5 +- src/Router/ReceiverMapRouter.php | 12 ++--- src/Router/ReceiverResolver.php | 5 +- src/Router/SimpleReceiverResolver.php | 8 +-- src/Serializer.php | 7 +-- src/Util.php | 4 +- tests/Command/ConsumeCommandTest.php | 8 +-- tests/Command/ProduceCommandTest.php | 12 +++-- tests/ConsumerTest.php | 42 ++++++++------- tests/Driver/Doctrine/AbstractDriverTest.php | 38 +++++++------- .../Doctrine/Command/AbstractCommandTest.php | 14 ++--- .../Doctrine/Command/BaseCommandTest.php | 16 +++--- .../Doctrine/Command/CreateCommandTest.php | 2 + .../Doctrine/Command/DropCommandTest.php | 2 + .../Doctrine/Command/UpdateCommandTest.php | 2 + .../Doctrine/ConnectionListenerTest.php | 8 +-- tests/Driver/Doctrine/MySQLDriverTest.php | 6 ++- .../Driver/Doctrine/PostgreSQLDriverTest.php | 6 ++- tests/Driver/Doctrine/SQLiteDriverTest.php | 6 ++- tests/Driver/InMemory/DriverTest.php | 4 +- tests/Driver/MongoDB/DriverFunctionalTest.php | 30 ++++++----- tests/Driver/MongoDB/DriverTest.php | 52 ++++++++++--------- tests/Driver/PrefetchMessageCacheTest.php | 4 +- tests/EnvelopeTest.php | 9 ++-- tests/Event/EnvelopeEventTest.php | 8 +-- tests/Event/RejectEnvelopeEventTest.php | 10 ++-- .../EventListener/ErrorLogSubscriberTest.php | 18 ++++--- tests/EventListener/FailureSubscriberTest.php | 6 ++- tests/EventListener/LoggerSubscriberTest.php | 10 ++-- tests/Fixtures/SendNewsletterMessage.php | 11 ++-- tests/Message/PlainMessageTest.php | 32 +++--------- .../Normalizer/PlainMessageNormalizerTest.php | 12 ++--- tests/ProducerTest.php | 14 ++--- tests/Queue/AbstractQueueTest.php | 8 +-- tests/Queue/InMemoryQueueTest.php | 6 ++- tests/Queue/PersistentQueueTest.php | 32 ++++++------ tests/Queue/RoundRobinQueueTest.php | 24 +++++---- tests/QueueFactory/InMemoryFactoryTest.php | 10 ++-- tests/QueueFactory/PersistentFactoryTest.php | 22 ++++---- 81 files changed, 460 insertions(+), 447 deletions(-) diff --git a/src/BernardEvents.php b/src/BernardEvents.php index 0233b1a4..f43b36a6 100644 --- a/src/BernardEvents.php +++ b/src/BernardEvents.php @@ -1,5 +1,7 @@ consumer = $consumer; @@ -31,7 +29,7 @@ public function __construct(Consumer $consumer, QueueFactory $queues) /** * {@inheritdoc} */ - public function configure() + public function configure(): void { $this ->addOption('max-runtime', null, InputOption::VALUE_OPTIONAL, 'Maximum time in seconds the consumer will run.', null) @@ -45,7 +43,7 @@ public function configure() /** * {@inheritdoc} */ - public function execute(InputInterface $input, OutputInterface $output) + public function execute(InputInterface $input, OutputInterface $output): void { $queue = $this->getQueue($input->getArgument('queue')); @@ -59,8 +57,8 @@ public function execute(InputInterface $input, OutputInterface $output) */ protected function getQueue($queue) { - if (is_array($queue)) { - if (count($queue) > 1) { + if (\is_array($queue)) { + if (\count($queue) > 1) { $queues = array_map([$this->queues, 'create'], $queue); return new RoundRobinQueue($queues); diff --git a/src/Command/ProduceCommand.php b/src/Command/ProduceCommand.php index be308b15..8de4b2dc 100644 --- a/src/Command/ProduceCommand.php +++ b/src/Command/ProduceCommand.php @@ -1,21 +1,20 @@ producer = $producer; @@ -26,7 +25,7 @@ public function __construct(Producer $producer) /** * {@inheritdoc} */ - public function configure() + public function configure(): void { $this ->addOption('queue', null, InputOption::VALUE_OPTIONAL, 'Name of a queue to add this job to. By default the queue is guessed from the message name.', null) @@ -38,7 +37,7 @@ public function configure() /** * {@inheritdoc} */ - public function execute(InputInterface $input, OutputInterface $output) + public function execute(InputInterface $input, OutputInterface $output): void { $name = $input->getArgument('name'); $queue = $input->getOption('queue'); diff --git a/src/Consumer.php b/src/Consumer.php index 2fefc087..f6b606a1 100644 --- a/src/Consumer.php +++ b/src/Consumer.php @@ -1,11 +1,13 @@ PHP_INT_MAX, + 'max-runtime' => \PHP_INT_MAX, 'max-messages' => null, 'stop-when-empty' => false, 'stop-on-error' => false, ]; - /** - * @param Router $router - * @param EventDispatcherInterface $dispatcher - */ public function __construct(Router $router, EventDispatcherInterface $dispatcher) { $this->router = $router; @@ -33,11 +31,8 @@ public function __construct(Router $router, EventDispatcherInterface $dispatcher /** * Starts an infinite loop calling Consumer::tick();. - * - * @param Queue $queue - * @param array $options */ - public function consume(Queue $queue, array $options = []) + public function consume(Queue $queue, array $options = []): void { declare(ticks=1); @@ -52,9 +47,6 @@ public function consume(Queue $queue, array $options = []) * Returns true do indicate it should be run again or false to indicate * it should not be run again. * - * @param Queue $queue - * @param array $options - * * @return bool */ public function tick(Queue $queue, array $options = []) @@ -91,7 +83,7 @@ public function tick(Queue $queue, array $options = []) /** * Mark Consumer as shutdown. */ - public function shutdown() + public function shutdown(): void { $this->shutdown = true; } @@ -99,7 +91,7 @@ public function shutdown() /** * Pause consuming. */ - public function pause() + public function pause(): void { $this->pause = true; } @@ -107,7 +99,7 @@ public function pause() /** * Resume consuming. */ - public function resume() + public function resume(): void { $this->pause = false; } @@ -116,13 +108,10 @@ public function resume() * Until there is a real extension point to doing invoked stuff, this can be used * by wrapping the invoke method. * - * @param Envelope $envelope - * @param Queue $queue - * * @throws \Exception * @throws \Throwable */ - public function invoke(Envelope $envelope, Queue $queue) + public function invoke(Envelope $envelope, Queue $queue): void { try { $this->dispatcher->dispatch(BernardEvents::INVOKE, new EnvelopeEvent($envelope, $queue)); @@ -141,9 +130,6 @@ public function invoke(Envelope $envelope, Queue $queue) } } - /** - * @param array $options - */ protected function configure(array $options) { if ($this->configured) { @@ -162,26 +148,24 @@ protected function configure(array $options) * The difference is that when terminating the consumer, running processes will not stop gracefully * and will terminate immediately. */ - protected function bind() + protected function bind(): void { - if (function_exists('pcntl_signal')) { - pcntl_signal(SIGTERM, [$this, 'shutdown']); - pcntl_signal(SIGINT, [$this, 'shutdown']); - pcntl_signal(SIGQUIT, [$this, 'shutdown']); - pcntl_signal(SIGUSR2, [$this, 'pause']); - pcntl_signal(SIGCONT, [$this, 'resume']); + if (\function_exists('pcntl_signal')) { + pcntl_signal(\SIGTERM, [$this, 'shutdown']); + pcntl_signal(\SIGINT, [$this, 'shutdown']); + pcntl_signal(\SIGQUIT, [$this, 'shutdown']); + pcntl_signal(\SIGUSR2, [$this, 'pause']); + pcntl_signal(\SIGCONT, [$this, 'resume']); } } /** * @param \Throwable|\Exception $exception note that the type-hint is missing due to PHP 5.x compat - * @param Envelope $envelope - * @param Queue $queue * * @throws \Exception * @throws \Throwable */ - private function rejectDispatch($exception, Envelope $envelope, Queue $queue) + private function rejectDispatch($exception, Envelope $envelope, Queue $queue): void { // Make sure the exception is not interfering. // Previously failing jobs handling have been moved to a middleware. diff --git a/src/Driver/Doctrine/Command/AbstractCommand.php b/src/Driver/Doctrine/Command/AbstractCommand.php index e767cf99..ef2e1b3c 100644 --- a/src/Driver/Doctrine/Command/AbstractCommand.php +++ b/src/Driver/Doctrine/Command/AbstractCommand.php @@ -1,5 +1,7 @@ addOption('dump-sql', null, InputOption::VALUE_NONE, 'Output generated SQL statements instead of applying them'); } @@ -29,19 +31,19 @@ public function configure() /** * {@inheritdoc} */ - public function execute(InputInterface $input, OutputInterface $output) + public function execute(InputInterface $input, OutputInterface $output): void { $schema = new Schema(); MessagesSchema::create($schema); $sync = $this->getSynchronizer($this->getHelper('connection')->getConnection()); if ($input->getOption('dump-sql')) { - $output->writeln(implode(';'.PHP_EOL, $this->getSql($sync, $schema)).';'); + $output->writeln(implode(';'.\PHP_EOL, $this->getSql($sync, $schema)).';'); return; } - $output->writeln('ATTENTION: This operation should not be executed in a production environment.'.PHP_EOL); + $output->writeln('ATTENTION: This operation should not be executed in a production environment.'.\PHP_EOL); $output->writeln('Applying database schema changes...'); $this->applySql($sync, $schema); $output->writeln('Schema changes applied successfully!'); @@ -56,16 +58,9 @@ protected function getSynchronizer(Connection $connection) } /** - * @param \Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer $sync - * @param \Doctrine\DBAL\Schema\Schema $schema - * * @return array */ abstract protected function getSql(Synchronizer $sync, Schema $schema); - /** - * @param \Doctrine\DBAL\Schema\Synchronizer\SingleDatabaseSynchronizer $sync - * @param \Doctrine\DBAL\Schema\Schema $schema - */ abstract protected function applySql(Synchronizer $sync, Schema $schema); } diff --git a/src/Driver/Doctrine/Command/CreateCommand.php b/src/Driver/Doctrine/Command/CreateCommand.php index abd571a3..ecddfa1a 100644 --- a/src/Driver/Doctrine/Command/CreateCommand.php +++ b/src/Driver/Doctrine/Command/CreateCommand.php @@ -1,5 +1,7 @@ createSchema($schema); } diff --git a/src/Driver/Doctrine/Command/DropCommand.php b/src/Driver/Doctrine/Command/DropCommand.php index d9cbaac9..e79bd7c4 100644 --- a/src/Driver/Doctrine/Command/DropCommand.php +++ b/src/Driver/Doctrine/Command/DropCommand.php @@ -1,5 +1,7 @@ dropSchema($schema); } diff --git a/src/Driver/Doctrine/Command/UpdateCommand.php b/src/Driver/Doctrine/Command/UpdateCommand.php index 72e09465..ab3837c2 100644 --- a/src/Driver/Doctrine/Command/UpdateCommand.php +++ b/src/Driver/Doctrine/Command/UpdateCommand.php @@ -1,5 +1,7 @@ updateSchema($schema); } diff --git a/src/Driver/Doctrine/ConnectionListener.php b/src/Driver/Doctrine/ConnectionListener.php index 5d8c0e38..24027174 100644 --- a/src/Driver/Doctrine/ConnectionListener.php +++ b/src/Driver/Doctrine/ConnectionListener.php @@ -1,9 +1,11 @@ connections = $connections; } - public function onPing() + public function onPing(): void { foreach ($this->connections as $connection) { if (!$connection->isConnected()) { diff --git a/src/Driver/Doctrine/MessagesSchema.php b/src/Driver/Doctrine/MessagesSchema.php index 439a35a5..36957af7 100644 --- a/src/Driver/Doctrine/MessagesSchema.php +++ b/src/Driver/Doctrine/MessagesSchema.php @@ -1,5 +1,7 @@ createTable('bernard_queues'); $table->addColumn('name', 'string'); @@ -31,10 +29,8 @@ protected static function createQueueTable(Schema $schema) /** * Creates message table on the current schema given. - * - * @param Schema $schema */ - protected static function createMessagesTable(Schema $schema) + protected static function createMessagesTable(Schema $schema): void { $table = $schema->createTable('bernard_messages'); $table->addColumn('id', 'integer', [ diff --git a/src/Driver/PrefetchMessageCache.php b/src/Driver/PrefetchMessageCache.php index 84727fca..c8aa8f97 100644 --- a/src/Driver/PrefetchMessageCache.php +++ b/src/Driver/PrefetchMessageCache.php @@ -14,7 +14,7 @@ final class PrefetchMessageCache /** * Pushes a $message to the bottom of the cache. */ - public function push(string $queueName, \Bernard\DriverMessage $message): void + public function push(string $queueName, essage $message): void { $cache = $this->get($queueName); $cache->enqueue($message); @@ -24,7 +24,7 @@ public function push(string $queueName, \Bernard\DriverMessage $message): void * Get the next message in line. Or nothing if there is no more * in the cache. */ - public function pop(string $queueName): ?\Bernard\DriverMessage + public function pop(string $queueName): ?essage { $cache = $this->get($queueName); diff --git a/src/Envelope.php b/src/Envelope.php index 1630e1a1..d2b69c7e 100644 --- a/src/Envelope.php +++ b/src/Envelope.php @@ -1,5 +1,7 @@ message = $message; - $this->class = get_class($message); + $this->class = $message::class; $this->timestamp = time(); } diff --git a/src/Event/EnvelopeEvent.php b/src/Event/EnvelopeEvent.php index 060a65fd..68ca2ed1 100644 --- a/src/Event/EnvelopeEvent.php +++ b/src/Event/EnvelopeEvent.php @@ -1,5 +1,7 @@ envelope = $envelope; diff --git a/src/Event/PingEvent.php b/src/Event/PingEvent.php index 77706d93..e1d2a663 100644 --- a/src/Event/PingEvent.php +++ b/src/Event/PingEvent.php @@ -1,5 +1,7 @@ queue = $queue; diff --git a/src/Event/RejectEnvelopeEvent.php b/src/Event/RejectEnvelopeEvent.php index da6a7d09..ec9eee84 100644 --- a/src/Event/RejectEnvelopeEvent.php +++ b/src/Event/RejectEnvelopeEvent.php @@ -1,5 +1,7 @@ format($event->getEnvelope(), $event->getException())); } /** - * @param Envelope $envelope - * @param mixed $exception + * @param mixed $exception * * @return string */ @@ -28,7 +26,7 @@ protected function format(Envelope $envelope, $exception) { if ($exception instanceof Exception || $exception instanceof Throwable) { $replacements = [ - '{class}' => get_class($exception), + '{class}' => $exception::class, '{message}' => $exception->getMessage(), '{envelope}' => $envelope->getName(), ]; @@ -37,7 +35,7 @@ protected function format(Envelope $envelope, $exception) } $replacements = [ - '{type}' => is_object($exception) ? get_class($exception) : gettype($exception), + '{type}' => \is_object($exception) ? $exception::class : \gettype($exception), '{envelope}' => $envelope->getName(), ]; diff --git a/src/EventListener/FailureSubscriber.php b/src/EventListener/FailureSubscriber.php index 22740db9..fa1ec2b1 100644 --- a/src/EventListener/FailureSubscriber.php +++ b/src/EventListener/FailureSubscriber.php @@ -1,5 +1,7 @@ name = $name; } - /** - * @param RejectEnvelopeEvent $event - */ - public function onReject(RejectEnvelopeEvent $event) + public function onReject(RejectEnvelopeEvent $event): void { $envelope = $event->getEnvelope(); $message = $envelope->getMessage(); diff --git a/src/EventListener/LoggerSubscriber.php b/src/EventListener/LoggerSubscriber.php index 171c3499..d878370c 100644 --- a/src/EventListener/LoggerSubscriber.php +++ b/src/EventListener/LoggerSubscriber.php @@ -1,5 +1,7 @@ logger = $logger; } - /** - * @param EnvelopeEvent $event - */ - public function onProduce(EnvelopeEvent $event) + public function onProduce(EnvelopeEvent $event): void { $this->logger->info('[bernard] produced {envelope} onto {queue}.', [ 'envelope' => $event->getEnvelope(), @@ -30,20 +26,14 @@ public function onProduce(EnvelopeEvent $event) ]); } - /** - * @param EnvelopeEvent $event - */ - public function onInvoke(EnvelopeEvent $event) + public function onInvoke(EnvelopeEvent $event): void { $this->logger->info('[bernard] invoking receiver for {envelope}.', [ 'envelope' => $event->getEnvelope(), ]); } - /** - * @param RejectEnvelopeEvent $event - */ - public function onReject(RejectEnvelopeEvent $event) + public function onReject(RejectEnvelopeEvent $event): void { $this->logger->error('[bernard] caught exception {exception} while processing {envelope}.', [ 'envelope' => $event->getEnvelope(), diff --git a/src/Exception.php b/src/Exception.php index 5bcc42a7..2891222e 100644 --- a/src/Exception.php +++ b/src/Exception.php @@ -1,5 +1,7 @@ arguments); + return \array_key_exists($name, $this->arguments); } public function offsetGet($offset) @@ -75,12 +76,12 @@ public function offsetExists($offset) return $this->has($offset); } - public function offsetSet($offset, $value) + public function offsetSet($offset, $value): void { throw new \LogicException('Message is immutable'); } - public function offsetUnset($offset) + public function offsetUnset($offset): void { throw new \LogicException('Message is immutable'); } @@ -95,12 +96,12 @@ public function __isset($property) return $this->has($property); } - public function __set($property, $value) + public function __set($property, $value): void { throw new \LogicException('Message is immutable'); } - public function __unset($property) + public function __unset($property): void { throw new \LogicException('Message is immutable'); } diff --git a/src/Normalizer/EnvelopeNormalizer.php b/src/Normalizer/EnvelopeNormalizer.php index 294dd93e..27db120c 100644 --- a/src/Normalizer/EnvelopeNormalizer.php +++ b/src/Normalizer/EnvelopeNormalizer.php @@ -1,5 +1,7 @@ aggregate = $aggregate; } @@ -73,11 +72,10 @@ public function supportsNormalization($data, $format = null) } /** - * @param Envelope $envelope - * @param string $property - * @param mixed $value + * @param string $property + * @param mixed $value */ - private function forcePropertyValue(Envelope $envelope, $property, $value) + private function forcePropertyValue(Envelope $envelope, $property, $value): void { try { $property = new \ReflectionProperty($envelope, $property); diff --git a/src/Normalizer/PlainMessageNormalizer.php b/src/Normalizer/PlainMessageNormalizer.php index a77953fb..964e4e56 100644 --- a/src/Normalizer/PlainMessageNormalizer.php +++ b/src/Normalizer/PlainMessageNormalizer.php @@ -1,13 +1,15 @@ queues = $queues; @@ -21,10 +19,9 @@ public function __construct(QueueFactory $queues, EventDispatcherInterface $disp } /** - * @param Message $message * @param string|null $queueName */ - public function produce(Message $message, $queueName = null) + public function produce(Message $message, $queueName = null): void { $queueName = $queueName ?: Util::guessQueue($message); @@ -34,7 +31,7 @@ public function produce(Message $message, $queueName = null) $this->dispatch(BernardEvents::PRODUCE, new EnvelopeEvent($envelope, $queue)); } - private function dispatch($eventName, EnvelopeEvent $event) + private function dispatch($eventName, EnvelopeEvent $event): void { $this->dispatcher instanceof \Symfony\Contracts\EventDispatcher\EventDispatcherInterface ? $this->dispatcher->dispatch($event, $eventName) diff --git a/src/Queue.php b/src/Queue.php index 0561681f..1660f970 100644 --- a/src/Queue.php +++ b/src/Queue.php @@ -1,12 +1,11 @@ closed = true; } @@ -31,7 +33,7 @@ public function close() * * {@inheritdoc} */ - public function acknowledge(Envelope $envelope) + public function acknowledge(Envelope $envelope): void { $this->errorIfClosed(); } @@ -39,7 +41,7 @@ public function acknowledge(Envelope $envelope) /** * @throws InvalidOperationException */ - protected function errorIfClosed() + protected function errorIfClosed(): void { if ($this->closed) { throw new InvalidOperationException(sprintf('Queue "%s" is closed.', $this->name)); diff --git a/src/Queue/InMemoryQueue.php b/src/Queue/InMemoryQueue.php index 9e57aac1..2fb0f829 100644 --- a/src/Queue/InMemoryQueue.php +++ b/src/Queue/InMemoryQueue.php @@ -1,5 +1,7 @@ errorIfClosed(); @@ -69,7 +71,7 @@ public function peek($index = 0, $limit = 20) $queue = clone $this->queue; $key = 0; - while ($queue->count() && count($envelopes) < $limit && $envelope = $queue->dequeue()) { + while ($queue->count() && \count($envelopes) < $limit && $envelope = $queue->dequeue()) { if ($key++ < $index) { continue; } diff --git a/src/Queue/PersistentQueue.php b/src/Queue/PersistentQueue.php index af1680e4..6057a05e 100644 --- a/src/Queue/PersistentQueue.php +++ b/src/Queue/PersistentQueue.php @@ -1,5 +1,7 @@ errorIfClosed(); @@ -51,7 +51,7 @@ public function count() /** * {@inheritdoc} */ - public function close() + public function close(): void { parent::close(); @@ -61,7 +61,7 @@ public function close() /** * {@inheritdoc} */ - public function enqueue(Envelope $envelope) + public function enqueue(Envelope $envelope): void { $this->errorIfClosed(); @@ -71,7 +71,7 @@ public function enqueue(Envelope $envelope) /** * {@inheritdoc} */ - public function acknowledge(Envelope $envelope) + public function acknowledge(Envelope $envelope): void { $this->errorIfClosed(); diff --git a/src/Queue/RoundRobinQueue.php b/src/Queue/RoundRobinQueue.php index b9e500ed..d9dddbb6 100644 --- a/src/Queue/RoundRobinQueue.php +++ b/src/Queue/RoundRobinQueue.php @@ -1,5 +1,7 @@ verifyEnvelope($envelope); @@ -52,7 +54,7 @@ public function dequeue() $envelope = null; $checked = []; - while (count($checked) < count($this->queues)) { + while (\count($checked) < \count($this->queues)) { $queue = current($this->queues); $envelope = $queue->dequeue(); if (false === next($this->queues)) { @@ -72,7 +74,7 @@ public function dequeue() /** * {@inheritdoc} */ - public function close() + public function close(): void { if ($this->closed) { return; @@ -102,7 +104,7 @@ public function peek($index = 0, $limit = 20) // noop } - while (count($envelopes) < $limit && count($drained) < $it->count()) { + while (\count($envelopes) < $limit && \count($drained) < $it->count()) { $queue = $it->current(); $name = $it->key(); if ($peeked = $queue->peek($indexes[$name], 1)) { @@ -124,12 +126,10 @@ public function peek($index = 0, $limit = 20) /** * {@inheritdoc} */ - public function acknowledge(Envelope $envelope) + public function acknowledge(Envelope $envelope): void { if (!$this->envelopes->contains($envelope)) { - throw new \DomainException( - 'Unrecognized queue specified: '.$envelope->getName() - ); + throw new \DomainException('Unrecognized queue specified: '.$envelope->getName()); } $queue = $this->envelopes[$envelope]; @@ -157,7 +157,7 @@ public function count() /** * @param Queue[] $queues */ - protected function validateQueues(array $queues) + protected function validateQueues(array $queues): void { if (empty($queues)) { throw new \DomainException('$queues cannot be empty'); @@ -165,9 +165,7 @@ protected function validateQueues(array $queues) $filtered = array_filter( $queues, - function ($queue) { - return !$queue instanceof Queue; - } + fn ($queue) => !$queue instanceof Queue ); if (!empty($filtered)) { throw new \DomainException('All elements of $queues must implement Queue'); @@ -183,19 +181,14 @@ protected function indexQueues(array $queues) { return array_combine( array_map( - function ($queue) { - return (string) $queue; - }, + fn ($queue) => (string) $queue, $queues ), $queues ); } - /** - * @param Envelope $envelope - */ - protected function verifyEnvelope(Envelope $envelope) + protected function verifyEnvelope(Envelope $envelope): void { $queue = $envelope->getName(); if (isset($this->queues[$queue])) { diff --git a/src/QueueFactory.php b/src/QueueFactory.php index 2d306cde..96c0889e 100644 --- a/src/QueueFactory.php +++ b/src/QueueFactory.php @@ -1,5 +1,7 @@ queues); + return \count($this->queues); } /** @@ -52,7 +54,7 @@ public function exists($queueName) /** * {@inheritdoc} */ - public function remove($queueName) + public function remove($queueName): void { if ($this->exists($queueName)) { $this->queues[$queueName]->close(); diff --git a/src/QueueFactory/PersistentFactory.php b/src/QueueFactory/PersistentFactory.php index a5382ffe..c452740d 100644 --- a/src/QueueFactory/PersistentFactory.php +++ b/src/QueueFactory/PersistentFactory.php @@ -1,5 +1,7 @@ queues = []; @@ -57,7 +55,7 @@ public function all() */ public function exists($queueName) { - return isset($this->queues[$queueName]) ?: in_array($queueName, $this->driver->listQueues()); + return isset($this->queues[$queueName]) ?: \in_array($queueName, $this->driver->listQueues()); } /** @@ -66,13 +64,13 @@ public function exists($queueName) #[\ReturnTypeWillChange] public function count() { - return count($this->driver->listQueues()); + return \count($this->driver->listQueues()); } /** * {@inheritdoc} */ - public function remove($queueName) + public function remove($queueName): void { if (!$this->exists($queueName)) { return; diff --git a/src/Receiver.php b/src/Receiver.php index 56d9e921..a171965f 100644 --- a/src/Receiver.php +++ b/src/Receiver.php @@ -1,5 +1,7 @@ callable, $message); + \call_user_func($this->callable, $message); } } diff --git a/src/Router.php b/src/Router.php index 6c924988..e01a2703 100644 --- a/src/Router.php +++ b/src/Router.php @@ -1,5 +1,7 @@ container = $container; diff --git a/src/Router/ReceiverMapRouter.php b/src/Router/ReceiverMapRouter.php index d3229464..8a32ec10 100644 --- a/src/Router/ReceiverMapRouter.php +++ b/src/Router/ReceiverMapRouter.php @@ -1,5 +1,7 @@ receiverResolver->accepts($receiver)) { throw new \InvalidArgumentException(sprintf('Receiver "%s" is not supported.', $receiver)); @@ -67,14 +65,12 @@ public function route(Envelope $envelope) */ protected function get($name) { - return isset($this->receivers[$name]) ? $this->receivers[$name] : null; + return $this->receivers[$name] ?? null; } /** * Returns the (message) name to look for in the receiver map. * - * @param Envelope $envelope - * * @return string */ protected function getName(Envelope $envelope) diff --git a/src/Router/ReceiverResolver.php b/src/Router/ReceiverResolver.php index baee3e42..76092f04 100644 --- a/src/Router/ReceiverResolver.php +++ b/src/Router/ReceiverResolver.php @@ -1,5 +1,7 @@ getName())]; } // Receiver is still not a callable which means it's not a valid receiver. - if (is_callable($receiver) == false) { + if (\is_callable($receiver) == false) { return null; } diff --git a/src/Serializer.php b/src/Serializer.php index fe6fc468..156f6a24 100644 --- a/src/Serializer.php +++ b/src/Serializer.php @@ -1,5 +1,7 @@ aggregate = $aggregate ?: $this->createAggregateNormalizer(); } /** - * @param Envelope $envelope - * * @return string */ public function serialize(Envelope $envelope) diff --git a/src/Util.php b/src/Util.php index 698ab5a9..99a3aa71 100644 --- a/src/Util.php +++ b/src/Util.php @@ -1,5 +1,7 @@ queues = new InMemoryFactory(); $this->consumer = $this->getMockBuilder('Bernard\Consumer') @@ -18,7 +20,7 @@ public function setUp(): void /** * @medium */ - public function testItConsumes() + public function testItConsumes(): void { $command = new ConsumeCommand($this->consumer, $this->queues); $queue = $this->queues->create('send-newsletter'); @@ -40,7 +42,7 @@ public function testItConsumes() ]); } - public function testItConsumesRoundRobin() + public function testItConsumesRoundRobin(): void { $command = new ConsumeCommand($this->consumer, $this->queues); diff --git a/tests/Command/ProduceCommandTest.php b/tests/Command/ProduceCommandTest.php index f3525be1..0141b102 100644 --- a/tests/Command/ProduceCommandTest.php +++ b/tests/Command/ProduceCommandTest.php @@ -1,22 +1,24 @@ producer = $this->getMockBuilder('Bernard\Producer') ->disableOriginalConstructor()->getMock(); } - public function testProduceMessageWithNoArguments() + public function testProduceMessageWithNoArguments(): void { $command = new ProduceCommand($this->producer); $message = new PlainMessage('SendNewsletter'); @@ -29,7 +31,7 @@ public function testProduceMessageWithNoArguments() ]); } - public function testInvalidJsonThrowsException() + public function testInvalidJsonThrowsException(): void { $this->expectException(\RuntimeException::class); @@ -42,7 +44,7 @@ public function testInvalidJsonThrowsException() ]); } - public function testItProducesMessageWithData() + public function testItProducesMessageWithData(): void { $command = new ProduceCommand($this->producer); $message = new PlainMessage('SendNewsletter', ['foo' => 'bar']); diff --git a/tests/ConsumerTest.php b/tests/ConsumerTest.php index 13fa363d..8376649d 100644 --- a/tests/ConsumerTest.php +++ b/tests/ConsumerTest.php @@ -1,17 +1,19 @@ router = $this->prophesize(Router::class); @@ -40,7 +42,7 @@ public function setUp(): void $this->consumer = new Consumer($this->router->reveal(), $this->dispatcher); } - public function testEmitsConsumeEvent() + public function testEmitsConsumeEvent(): void { $envelope = new Envelope($message = new PlainMessage('ImportUsers')); @@ -69,7 +71,7 @@ public function testEmitsConsumeEvent() $this->assertTrue($this->consumer->tick($queue)); } - public function testEmitsExceptionEvent() + public function testEmitsExceptionEvent(): void { $exception = new \InvalidArgumentException(); @@ -87,7 +89,7 @@ public function testEmitsExceptionEvent() $this->consumer->invoke($envelope, $queue); } - public function testShutdown() + public function testShutdown(): void { $queue = new InMemoryQueue('queue'); @@ -96,7 +98,7 @@ public function testShutdown() $this->assertFalse($this->consumer->tick($queue)); } - public function testPauseResume() + public function testPauseResume(): void { $envelope = new Envelope($message = new PlainMessage('ImportUsers')); $queue = new InMemoryQueue('queue'); @@ -116,22 +118,22 @@ public function testPauseResume() $this->assertTrue($this->consumer->tick($queue)); } - public function testMaxRuntime() + public function testMaxRuntime(): void { $queue = new InMemoryQueue('queue'); $this->assertFalse($this->consumer->tick($queue, [ - 'max-runtime' => -1 * PHP_INT_MAX, + 'max-runtime' => -1 * \PHP_INT_MAX, ])); } - public function testNoEnvelopeInQueue() + public function testNoEnvelopeInQueue(): void { $queue = new InMemoryQueue('queue'); $this->assertTrue($this->consumer->tick($queue)); } - public function testEnvelopeIsAcknowledged() + public function testEnvelopeIsAcknowledged(): void { $envelope = new Envelope($message = new PlainMessage('ImportUsers')); @@ -141,13 +143,13 @@ public function testEnvelopeIsAcknowledged() $this->router->route($envelope)->willReturn($receiver); $queue = $this->createMock('Bernard\Queue'); - $queue->expects($this->once())->method('dequeue')->will($this->returnValue($envelope)); + $queue->expects($this->once())->method('dequeue')->willReturn($envelope); $queue->expects($this->once())->method('acknowledge')->with($this->equalTo($envelope)); $this->consumer->tick($queue); } - public function testMaxMessages() + public function testMaxMessages(): void { $envelope1 = new Envelope($message1 = new PlainMessage('ImportUsers')); $envelope2 = new Envelope($message2 = new PlainMessage('ImportUsers')); @@ -172,7 +174,7 @@ public function testMaxMessages() $this->assertTrue($this->consumer->tick($queue, ['max-messages' => 100])); } - public function testStopAfterLastMessage() + public function testStopAfterLastMessage(): void { $envelope1 = new Envelope($message1 = new PlainMessage('ImportUsers')); $envelope2 = new Envelope($message2 = new PlainMessage('ImportUsers')); @@ -193,7 +195,7 @@ public function testStopAfterLastMessage() $this->assertFalse($this->consumer->tick($queue, ['stop-when-empty' => true])); } - public function testStopOnError() + public function testStopOnError(): void { $this->expectException(\Bernard\Exception\ReceiverNotFoundException::class); @@ -212,7 +214,7 @@ public function testStopOnError() /** * @group debug */ - public function testEnvelopeWillBeInvoked() + public function testEnvelopeWillBeInvoked(): void { $envelope = new Envelope($message = new PlainMessage('ImportUsers')); @@ -230,7 +232,7 @@ public function testEnvelopeWillBeInvoked() /** * @requires PHP 7.0 */ - public function testWillRejectDispatchOnThrowableError() + public function testWillRejectDispatchOnThrowableError(): void { $this->expectException(\TypeError::class); diff --git a/tests/Driver/Doctrine/AbstractDriverTest.php b/tests/Driver/Doctrine/AbstractDriverTest.php index 601d1fd7..f7761711 100644 --- a/tests/Driver/Doctrine/AbstractDriverTest.php +++ b/tests/Driver/Doctrine/AbstractDriverTest.php @@ -1,9 +1,11 @@ markTestSkipped('Doctrine have incompatibility issues with HHVM.'); } @@ -49,7 +51,7 @@ protected function tearDown(): void } } - public function testPopMessageWithInterval() + public function testPopMessageWithInterval(): void { $microtime = microtime(true); @@ -58,7 +60,7 @@ public function testPopMessageWithInterval() $this->assertGreaterThanOrEqual(0.001, microtime(true) - $microtime); } - public function testCreateAndRemoveQueue() + public function testCreateAndRemoveQueue(): void { // Duplicates are not taking into account. $this->driver->createQueue('import-users'); @@ -72,13 +74,13 @@ public function testCreateAndRemoveQueue() $this->assertEquals(['send-newsletter'], $this->driver->listQueues()); } - public function testPushMessageLazilyCreatesQueue() + public function testPushMessageLazilyCreatesQueue(): void { $this->driver->pushMessage('send-newsletter', 'something'); $this->assertEquals(['send-newsletter'], $this->driver->listQueues()); } - public function testRemoveQueueRemovesMessages() + public function testRemoveQueueRemovesMessages(): void { $this->driver->pushMessage('send-newsletter', 'something'); $this->assertEquals(1, $this->driver->countMessages('send-newsletter')); @@ -88,7 +90,7 @@ public function testRemoveQueueRemovesMessages() $this->assertEquals(0, $this->driver->countMessages('send-newsletter')); } - public function testItIsAQueue() + public function testItIsAQueue(): void { $messages = array_map(function ($i) { $this->driver->pushMessage('send-newsletter', $message = 'my-message-'.$i); @@ -96,7 +98,7 @@ public function testItIsAQueue() return $message; }, range(1, 6)); - $assertPeek = function (array $peeked, $expectedCount) use ($messages) { + $assertPeek = function (array $peeked, $expectedCount) use ($messages): void { self::assertCount($expectedCount, $peeked); foreach ($peeked as $peek) { self::assertContains($peek, $messages); @@ -111,16 +113,16 @@ public function testItIsAQueue() $this->assertEquals([], $this->driver->peekQueue('import-users')); // popping - list($message, $id) = $this->driver->popMessage('send-newsletter'); + [$message, $id] = $this->driver->popMessage('send-newsletter'); self::assertContains($message, $messages); - list($message, $id) = $this->driver->popMessage('send-newsletter'); + [$message, $id] = $this->driver->popMessage('send-newsletter'); self::assertContains($message, $messages); // No messages when all are invisible $this->assertNull($this->driver->popMessage('import-users', 0.0001)); } - public function testCountMessages() + public function testCountMessages(): void { $this->assertEquals(0, $this->driver->countMessages('import-users')); @@ -128,13 +130,13 @@ public function testCountMessages() $this->driver->pushMessage('send-newsletter', 'my-message-2'); $this->assertEquals(2, $this->driver->countMessages('send-newsletter')); - list($message, $id) = $this->driver->popMessage('send-newsletter'); + [$message, $id] = $this->driver->popMessage('send-newsletter'); $this->driver->acknowledgeMessage('send-newsletter', $id); $this->assertEquals(1, $this->driver->countMessages('send-newsletter')); } - public function testPeekMessagesExcludesPoppedMessages() + public function testPeekMessagesExcludesPoppedMessages(): void { $this->driver->pushMessage('send-newsletter', 'my-message-1'); $this->driver->pushMessage('send-newsletter', 'my-message-2'); @@ -149,7 +151,7 @@ public function testPeekMessagesExcludesPoppedMessages() $this->assertEquals(2, $this->driver->countMessages('send-newsletter')); } - public function testListQueues() + public function testListQueues(): void { $this->driver->pushMessage('import', 'message1'); $this->driver->pushMessage('send-newsletter', 'message2'); @@ -157,7 +159,7 @@ public function testListQueues() $this->assertEquals(['import', 'send-newsletter'], $this->driver->listQueues()); } - public function testRemoveQueue() + public function testRemoveQueue(): void { $this->driver->pushMessage('import', 'message1'); $this->driver->pushMessage('import', 'message2'); @@ -168,12 +170,12 @@ public function testRemoveQueue() $this->assertEquals(0, $this->driver->countMessages('import')); } - protected function insertMessage($queue, $message) + protected function insertMessage($queue, $message): void { $this->connection->insert('messages', compact('queue', 'message')); } - protected function setUpDatabase() + protected function setUpDatabase(): void { $this->connection = $this->createConnection(); diff --git a/tests/Driver/Doctrine/Command/AbstractCommandTest.php b/tests/Driver/Doctrine/Command/AbstractCommandTest.php index 3872399f..92e8542f 100644 --- a/tests/Driver/Doctrine/Command/AbstractCommandTest.php +++ b/tests/Driver/Doctrine/Command/AbstractCommandTest.php @@ -1,5 +1,7 @@ getMockBuilder('Doctrine\\DBAL\\Connection') ->disableOriginalConstructor()->getMock(); @@ -19,7 +21,7 @@ public function setUp(): void $helper ->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($connection)); + ->willReturn($connection); $this->command = $this->getMockBuilder(AbstractCommand::class) ->setMethods(['getSql', 'applySql', 'getHelper']) @@ -29,10 +31,10 @@ public function setUp(): void ->expects($this->any()) ->method('getHelper') ->with('connection') - ->will($this->returnValue($helper)); + ->willReturn($helper); } - public function testExecuteWithDumpSql() + public function testExecuteWithDumpSql(): void { $this->command ->expects($this->once()) @@ -41,7 +43,7 @@ public function testExecuteWithDumpSql() $this->isInstanceOf('Doctrine\\DBAL\\Schema\\Synchronizer\\SingleDatabaseSynchronizer'), $this->isInstanceOf('Doctrine\\DBAL\\Schema\\Schema') ) - ->will($this->returnValue([])); + ->willReturn([]); $tester = new CommandTester($this->command); $tester->execute([ @@ -49,7 +51,7 @@ public function testExecuteWithDumpSql() ]); } - public function testExecuteWithoutDumpSql() + public function testExecuteWithoutDumpSql(): void { $this->command ->expects($this->once()) diff --git a/tests/Driver/Doctrine/Command/BaseCommandTest.php b/tests/Driver/Doctrine/Command/BaseCommandTest.php index 328a1a61..2b0c630b 100644 --- a/tests/Driver/Doctrine/Command/BaseCommandTest.php +++ b/tests/Driver/Doctrine/Command/BaseCommandTest.php @@ -1,5 +1,7 @@ getMockBuilder('Doctrine\\DBAL\\Connection') ->disableOriginalConstructor()->getMock(); @@ -23,7 +25,7 @@ public function setUp(): void $helper ->expects($this->any()) ->method('getConnection') - ->will($this->returnValue($connection)); + ->willReturn($connection); $this->command = $this->getMockBuilder('Bernard\\Driver\\Doctrine\\Command\\'.$this->getShortClassName()) ->setMethods(['getSynchronizer', 'getHelper']) @@ -33,21 +35,21 @@ public function setUp(): void ->expects($this->any()) ->method('getSynchronizer') ->with($connection) - ->will($this->returnValue($this->sync)); + ->willReturn($this->sync); $this->command ->expects($this->any()) ->method('getHelper') ->with('connection') - ->will($this->returnValue($helper)); + ->willReturn($helper); } - public function testExecuteWithDumpSql() + public function testExecuteWithDumpSql(): void { $this->sync ->expects($this->once()) ->method($this->getSqlMethod()) ->with($this->isInstanceOf('Doctrine\\DBAL\\Schema\\Schema')) - ->will($this->returnValue([])); + ->willReturn([]); $tester = new CommandTester($this->command); $tester->execute([ @@ -55,7 +57,7 @@ public function testExecuteWithDumpSql() ]); } - public function testExecuteWithoutDumpSql() + public function testExecuteWithoutDumpSql(): void { $this->sync ->expects($this->once()) diff --git a/tests/Driver/Doctrine/Command/CreateCommandTest.php b/tests/Driver/Doctrine/Command/CreateCommandTest.php index 1e31381a..cbc5ed32 100644 --- a/tests/Driver/Doctrine/Command/CreateCommandTest.php +++ b/tests/Driver/Doctrine/Command/CreateCommandTest.php @@ -1,5 +1,7 @@ listener = new ConnectionListener($this->connection->reveal()); } - public function testPing() + public function testPing(): void { $this->connection->isConnected()->willReturn(true); @@ -27,14 +29,14 @@ public function testPing() $this->listener->onPing(); } - public function testPingOnNotConnectedConnection() + public function testPingOnNotConnectedConnection(): void { $this->connection->isConnected()->willReturn(false); $this->listener->onPing(); } - public function testCloseConnectionIfPingFails() + public function testCloseConnectionIfPingFails(): void { $this->connection->isConnected()->willReturn(true); $this->connection->query('SELECT 1')->willThrow(new DBALException()); diff --git a/tests/Driver/Doctrine/MySQLDriverTest.php b/tests/Driver/Doctrine/MySQLDriverTest.php index 5a859833..896da1d6 100644 --- a/tests/Driver/Doctrine/MySQLDriverTest.php +++ b/tests/Driver/Doctrine/MySQLDriverTest.php @@ -1,5 +1,7 @@ 'pdo_mysql', diff --git a/tests/Driver/Doctrine/PostgreSQLDriverTest.php b/tests/Driver/Doctrine/PostgreSQLDriverTest.php index 8339dfb9..d4b78b84 100644 --- a/tests/Driver/Doctrine/PostgreSQLDriverTest.php +++ b/tests/Driver/Doctrine/PostgreSQLDriverTest.php @@ -1,5 +1,7 @@ 'pdo_pgsql', diff --git a/tests/Driver/Doctrine/SQLiteDriverTest.php b/tests/Driver/Doctrine/SQLiteDriverTest.php index 13b7d9bd..4de20e71 100644 --- a/tests/Driver/Doctrine/SQLiteDriverTest.php +++ b/tests/Driver/Doctrine/SQLiteDriverTest.php @@ -1,5 +1,7 @@ true, diff --git a/tests/Driver/InMemory/DriverTest.php b/tests/Driver/InMemory/DriverTest.php index 0a7bb963..f8553fb0 100644 --- a/tests/Driver/InMemory/DriverTest.php +++ b/tests/Driver/InMemory/DriverTest.php @@ -1,5 +1,7 @@ driver->createQueue('queue1'); $this->driver->createQueue('queue2'); diff --git a/tests/Driver/MongoDB/DriverFunctionalTest.php b/tests/Driver/MongoDB/DriverFunctionalTest.php index 928ddc1d..a0e69529 100644 --- a/tests/Driver/MongoDB/DriverFunctionalTest.php +++ b/tests/Driver/MongoDB/DriverFunctionalTest.php @@ -1,5 +1,7 @@ markTestSkipped('MongoDB extension is not available.'); @@ -43,7 +45,7 @@ public function setUp(): void $this->driver = new Driver($this->queues, $this->messages); } - public function tearDown(): void + protected function tearDown(): void { if (!$this->messages instanceof MongoCollection) { return; @@ -60,7 +62,7 @@ public function tearDown(): void * @covers ::popMessage() * @covers ::pushMessage() */ - public function testMessageLifecycle() + public function testMessageLifecycle(): void { $this->assertEquals(0, $this->driver->countMessages('foo')); @@ -70,17 +72,17 @@ public function testMessageLifecycle() $this->driver->pushMessage('foo', 'message2'); $this->assertEquals(2, $this->driver->countMessages('foo')); - list($message1, $receipt1) = $this->driver->popMessage('foo'); + [$message1, $receipt1] = $this->driver->popMessage('foo'); $this->assertSame('message1', $message1, 'The first message pushed is popped first'); $this->assertRegExp('/^[a-f\d]{24}$/i', $receipt1, 'The message receipt is an ObjectId'); $this->assertEquals(1, $this->driver->countMessages('foo')); - list($message2, $receipt2) = $this->driver->popMessage('foo'); + [$message2, $receipt2] = $this->driver->popMessage('foo'); $this->assertSame('message2', $message2, 'The second message pushed is popped second'); $this->assertRegExp('/^[a-f\d]{24}$/i', $receipt2, 'The message receipt is an ObjectId'); $this->assertEquals(0, $this->driver->countMessages('foo')); - list($message3, $receipt3) = $this->driver->popMessage('foo', 1); + [$message3, $receipt3] = $this->driver->popMessage('foo', 1); $this->assertNull($message3, 'Null message is returned when popping an empty queue'); $this->assertNull($receipt3, 'Null receipt is returned when popping an empty queue'); @@ -93,7 +95,7 @@ public function testMessageLifecycle() $this->assertEquals(0, $this->messages->count(), 'Acknowledged messages are removed from the database'); } - public function testPeekQueue() + public function testPeekQueue(): void { $this->driver->pushMessage('foo', 'message1'); $this->driver->pushMessage('foo', 'message2'); @@ -110,7 +112,7 @@ public function testPeekQueue() * @covers ::listQueues() * @covers ::removeQueue() */ - public function testQueueLifecycle() + public function testQueueLifecycle(): void { $this->driver->createQueue('foo'); $this->driver->createQueue('bar'); @@ -128,7 +130,7 @@ public function testQueueLifecycle() $this->assertContains('bar', $queues); } - public function testRemoveQueueDeletesMessages() + public function testRemoveQueueDeletesMessages(): void { $this->driver->pushMessage('foo', 'message1'); $this->driver->pushMessage('foo', 'message2'); @@ -140,7 +142,7 @@ public function testRemoveQueueDeletesMessages() $this->assertEquals(0, $this->messages->count()); } - public function testCreateQueueWithDuplicateNameIsNoop() + public function testCreateQueueWithDuplicateNameIsNoop(): void { $this->driver->createQueue('foo'); $this->driver->createQueue('foo'); @@ -148,7 +150,7 @@ public function testCreateQueueWithDuplicateNameIsNoop() $this->assertSame(['foo'], $this->driver->listQueues()); } - public function testInfo() + public function testInfo(): void { $info = [ 'messages' => self::DATABASE.'.'.self::MESSAGES, diff --git a/tests/Driver/MongoDB/DriverTest.php b/tests/Driver/MongoDB/DriverTest.php index 9011f384..ec3bbed6 100644 --- a/tests/Driver/MongoDB/DriverTest.php +++ b/tests/Driver/MongoDB/DriverTest.php @@ -1,9 +1,11 @@ markTestSkipped('MongoDB extension is not available.'); @@ -29,17 +31,17 @@ public function setUp(): void $this->driver = new Driver($this->queues, $this->messages); } - public function testListQueues() + public function testListQueues(): void { $this->queues->expects($this->once()) ->method('distinct') ->with('_id') - ->will($this->returnValue(['foo', 'bar'])); + ->willReturn(['foo', 'bar']); $this->assertSame(['foo', 'bar'], $this->driver->listQueues()); } - public function testCreateQueue() + public function testCreateQueue(): void { $this->queues->expects($this->once()) ->method('update') @@ -48,17 +50,17 @@ public function testCreateQueue() $this->driver->createQueue('foo'); } - public function testCountMessages() + public function testCountMessages(): void { $this->messages->expects($this->once()) ->method('count') ->with(['queue' => 'foo', 'visible' => true]) - ->will($this->returnValue(2)); + ->willReturn(2); $this->assertSame(2, $this->driver->countMessages('foo')); } - public function testPushMessage() + public function testPushMessage(): void { $this->messages->expects($this->once()) ->method('insert') @@ -72,7 +74,7 @@ public function testPushMessage() $this->driver->pushMessage('foo', 'message1'); } - public function testPopMessageWithFoundMessage() + public function testPopMessageWithFoundMessage(): void { $this->messages->expects($this->atLeastOnce()) ->method('findAndModify') @@ -82,9 +84,9 @@ public function testPopMessageWithFoundMessage() ['message' => 1], ['sort' => ['sentAt' => 1]] ) - ->will($this->returnValue(['message' => 'message1', '_id' => '000000000000000000000000'])); + ->willReturn(['message' => 'message1', '_id' => '000000000000000000000000']); - list($message, $receipt) = $this->driver->popMessage('foo'); + [$message, $receipt] = $this->driver->popMessage('foo'); $this->assertSame('message1', $message); $this->assertSame('000000000000000000000000', $receipt); } @@ -92,7 +94,7 @@ public function testPopMessageWithFoundMessage() /** * @medium */ - public function testPopMessageWithMissingMessage() + public function testPopMessageWithMissingMessage(): void { $this->messages->expects($this->atLeastOnce()) ->method('findAndModify') @@ -102,14 +104,14 @@ public function testPopMessageWithMissingMessage() ['message' => 1], ['sort' => ['sentAt' => 1]] ) - ->will($this->returnValue(false)); + ->willReturn(false); - list($message, $receipt) = $this->driver->popMessage('foo', 1); + [$message, $receipt] = $this->driver->popMessage('foo', 1); $this->assertNull($message); $this->assertNull($receipt); } - public function testAcknowledgeMessage() + public function testAcknowledgeMessage(): void { $this->messages->expects($this->once()) ->method('remove') @@ -122,7 +124,7 @@ public function testAcknowledgeMessage() $this->driver->acknowledgeMessage('foo', '000000000000000000000000'); } - public function testPeekQueue() + public function testPeekQueue(): void { $cursor = $this->getMockBuilder('MongoCursor') ->disableOriginalConstructor() @@ -131,32 +133,32 @@ public function testPeekQueue() $this->messages->expects($this->once()) ->method('find') ->with(['queue' => 'foo', 'visible' => true], ['_id' => 0, 'message' => 1]) - ->will($this->returnValue($cursor)); + ->willReturn($cursor); $cursor->expects($this->at(0)) ->method('sort') ->with(['sentAt' => 1]) - ->will($this->returnValue($cursor)); + ->willReturn($cursor); $cursor->expects($this->at(1)) ->method('limit') ->with(20) - ->will($this->returnValue($cursor)); + ->willReturn($cursor); /* Rather than mock MongoCursor's iterator interface, take advantage of * the final fluent method call and return an ArrayIterator. */ $cursor->expects($this->at(2)) ->method('skip') ->with(0) - ->will($this->returnValue(new ArrayIterator([ + ->willReturn(new ArrayIterator([ ['message' => 'message1'], ['message' => 'message2'], - ]))); + ])); $this->assertSame(['message1', 'message2'], $this->driver->peekQueue('foo')); } - public function testRemoveQueue() + public function testRemoveQueue(): void { $this->queues->expects($this->once()) ->method('remove') @@ -169,15 +171,15 @@ public function testRemoveQueue() $this->driver->removeQueue('foo'); } - public function testInfo() + public function testInfo(): void { $this->queues->expects($this->once()) ->method('__toString') - ->will($this->returnValue('db.queues')); + ->willReturn('db.queues'); $this->messages->expects($this->once()) ->method('__toString') - ->will($this->returnValue('db.messages')); + ->willReturn('db.messages'); $info = [ 'messages' => 'db.messages', diff --git a/tests/Driver/PrefetchMessageCacheTest.php b/tests/Driver/PrefetchMessageCacheTest.php index d14b8c54..17db97ec 100644 --- a/tests/Driver/PrefetchMessageCacheTest.php +++ b/tests/Driver/PrefetchMessageCacheTest.php @@ -1,12 +1,14 @@ getMockBuilder(Message::class)->disableOriginalConstructor() ->getMock(); @@ -16,12 +18,12 @@ public function setUp(): void $this->queue = $this->createMock('Bernard\Queue'); } - public function testIsEvent() + public function testIsEvent(): void { $this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', new EnvelopeEvent($this->envelope, $this->queue)); } - public function hasEnvelopeAndQueue() + public function hasEnvelopeAndQueue(): void { $event = new EnvelopeEvent($this->envelope, $this->queue); diff --git a/tests/Event/RejectEnvelopeEventTest.php b/tests/Event/RejectEnvelopeEventTest.php index a6813711..3c95d433 100644 --- a/tests/Event/RejectEnvelopeEventTest.php +++ b/tests/Event/RejectEnvelopeEventTest.php @@ -1,5 +1,7 @@ getMockBuilder(Message::class)->disableOriginalConstructor() ->getMock(); @@ -26,14 +28,14 @@ public function setUp(): void $this->queue = $this->createMock('Bernard\Queue'); } - public function testExtendsEnvelopeEvent() + public function testExtendsEnvelopeEvent(): void { $event = new RejectEnvelopeEvent($this->envelope, $this->queue, new \Exception()); $this->assertInstanceOf('Bernard\Event\EnvelopeEvent', $event); } - public function testRetrieveException() + public function testRetrieveException(): void { $e = new \Exception(); $event = new RejectEnvelopeEvent($this->envelope, $this->queue, $e); @@ -44,7 +46,7 @@ public function testRetrieveException() /** * @requires PHP 7.0 */ - public function testCanContainThrowable() + public function testCanContainThrowable(): void { $error = new \TypeError(); $event = new RejectEnvelopeEvent($this->envelope, $this->queue, $error); diff --git a/tests/EventListener/ErrorLogSubscriberTest.php b/tests/EventListener/ErrorLogSubscriberTest.php index 28dc6501..848c9f41 100644 --- a/tests/EventListener/ErrorLogSubscriberTest.php +++ b/tests/EventListener/ErrorLogSubscriberTest.php @@ -1,5 +1,7 @@ markTestSkipped("HHVM does not support `ini_set('error_log', '/path/to/log')`"); } @@ -29,19 +31,19 @@ public function setUp(): void $this->queue = $this->createMock('Bernard\Queue'); $this->producer = $this->getMockBuilder('Bernard\Producer')->disableOriginalConstructor()->getMock(); $this->subscriber = new ErrorLogSubscriber($this->producer, 'failures'); - $this->iniErrorLog = ini_get('error_log'); + $this->iniErrorLog = \ini_get('error_log'); $this->errorLogFile = tempnam(sys_get_temp_dir(), 'phpunit'); ini_set('error_log', $this->errorLogFile); ini_set('error_log', $this->errorLogFile); } - public function tearDown(): void + protected function tearDown(): void { ini_set('error_log', $this->iniErrorLog); unlink($this->errorLogFile); } - public function testGetSubscribedEvents() + public function testGetSubscribedEvents(): void { $expected = [ 'bernard.reject' => ['onReject'], @@ -50,7 +52,7 @@ public function testGetSubscribedEvents() $this->assertEquals($expected, $actual); } - public function testOnRejectException() + public function testOnRejectException(): void { $this->message->expects($this->once()) ->method('getName') @@ -66,7 +68,7 @@ public function testOnRejectException() /** * @requires PHP 7.0 */ - public function testOnRejectError() + public function testOnRejectError(): void { $this->message->expects($this->once()) ->method('getName') @@ -79,7 +81,7 @@ public function testOnRejectError() $this->assertStringEndsWith($expected, $actual); } - public function testOnRejectObject() + public function testOnRejectObject(): void { $this->message->expects($this->once()) ->method('getName') diff --git a/tests/EventListener/FailureSubscriberTest.php b/tests/EventListener/FailureSubscriberTest.php index 5929c7c0..6f92d397 100644 --- a/tests/EventListener/FailureSubscriberTest.php +++ b/tests/EventListener/FailureSubscriberTest.php @@ -1,5 +1,7 @@ producer = $this->getMockBuilder('Bernard\Producer')->disableOriginalConstructor()->getMock(); $this->subscriber = new FailureSubscriber($this->producer, 'failures'); } - public function testAcknowledgeMessageAndEnqueue() + public function testAcknowledgeMessageAndEnqueue(): void { $envelope = new Envelope($message = new PlainMessage('bar')); diff --git a/tests/EventListener/LoggerSubscriberTest.php b/tests/EventListener/LoggerSubscriberTest.php index c4f16160..cd2b8c57 100644 --- a/tests/EventListener/LoggerSubscriberTest.php +++ b/tests/EventListener/LoggerSubscriberTest.php @@ -1,5 +1,7 @@ getMockBuilder(LoggerInterface::class)->getMock(); $loggerMock->expects($this->once())->method('info'); @@ -18,7 +20,7 @@ public function testLogsInfoOnProduce() $subscriber->onProduce($this->prophesize(EnvelopeEvent::class)->reveal()); } - public function testsLogsInfoOnInvoke() + public function testsLogsInfoOnInvoke(): void { $loggerMock = $this->getMockBuilder(LoggerInterface::class)->getMock(); $loggerMock->expects($this->once())->method('info'); @@ -27,7 +29,7 @@ public function testsLogsInfoOnInvoke() $subscriber->onInvoke($this->prophesize(EnvelopeEvent::class)->reveal()); } - public function testLogsErrorOnReject() + public function testLogsErrorOnReject(): void { $loggerMock = $this->getMockBuilder(LoggerInterface::class)->getMock(); $loggerMock->expects($this->once())->method('error'); @@ -36,7 +38,7 @@ public function testLogsErrorOnReject() $subscriber->onReject($this->prophesize(RejectEnvelopeEvent::class)->reveal()); } - public function testGetSubscribedEvents() + public function testGetSubscribedEvents(): void { $events = LoggerSubscriber::getSubscribedEvents(); $expectedEvents = [ diff --git a/tests/Fixtures/SendNewsletterMessage.php b/tests/Fixtures/SendNewsletterMessage.php index 0fe779aa..85195257 100644 --- a/tests/Fixtures/SendNewsletterMessage.php +++ b/tests/Fixtures/SendNewsletterMessage.php @@ -1,20 +1,23 @@ newsletterId = $data['newsletterId']; } diff --git a/tests/Message/PlainMessageTest.php b/tests/Message/PlainMessageTest.php index a0186dbe..2e736514 100644 --- a/tests/Message/PlainMessageTest.php +++ b/tests/Message/PlainMessageTest.php @@ -1,15 +1,14 @@ 1, @@ -30,18 +29,12 @@ public function it_has_arguments() $this->assertNull($message->key3); } - /** - * @test - */ - public function it_implements_ArrayAccess() + public function testItImplementsArrayAccess(): void { $this->assertInstanceOf(\ArrayAccess::class, new PlainMessage('SendNewsletter')); } - /** - * @test - */ - public function it_is_immutable_to_magic_set() + public function testItIsImmutableToMagicSet(): void { $this->expectException(\LogicException::class); @@ -49,10 +42,7 @@ public function it_is_immutable_to_magic_set() $message->key1 = 1; } - /** - * @test - */ - public function it_is_immutable_to_magic_unset() + public function testItIsImmutableToMagicUnset(): void { $this->expectException(\LogicException::class); @@ -60,10 +50,7 @@ public function it_is_immutable_to_magic_unset() unset($message->key1); } - /** - * @test - */ - public function it_is_immutable_to_offset_set() + public function testItIsImmutableToOffsetSet(): void { $this->expectException(\LogicException::class); @@ -71,10 +58,7 @@ public function it_is_immutable_to_offset_set() $message['key1'] = 1; } - /** - * @test - */ - public function it_is_immutable_to_offset_unset() + public function testItIsImmutableToOffsetUnset(): void { $this->expectException(\LogicException::class); diff --git a/tests/Normalizer/PlainMessageNormalizerTest.php b/tests/Normalizer/PlainMessageNormalizerTest.php index 6f0d11b0..6a404b2d 100644 --- a/tests/Normalizer/PlainMessageNormalizerTest.php +++ b/tests/Normalizer/PlainMessageNormalizerTest.php @@ -1,5 +1,7 @@ assertEquals(['name' => 'foobar', 'arguments' => []], $normalized); } - /** - * @test - */ - public function it_denormalizes_a_normalized_message() + public function testItDenormalizesANormalizedMessage(): void { $normalizer = new PlainMessageNormalizer(); diff --git a/tests/ProducerTest.php b/tests/ProducerTest.php index 7346d8b4..9157b657 100644 --- a/tests/ProducerTest.php +++ b/tests/ProducerTest.php @@ -1,26 +1,28 @@ queues = new InMemoryFactory(); $this->dispatcher = new EventDispatcher(); $this->producer = new Producer($this->queues, $this->dispatcher); } - public function testDispatchesEvent() + public function testDispatchesEvent(): void { $args = []; - $this->dispatcher->addListener('bernard.produce', function ($event) use (&$args) { + $this->dispatcher->addListener('bernard.produce', function ($event) use (&$args): void { $args = ['envelope' => $event->getEnvelope(), 'queue' => $event->getQueue()]; }); @@ -32,7 +34,7 @@ public function testDispatchesEvent() $this->assertSame($this->queues->create('my-queue'), $args['queue']); } - public function testItDelegatesMessagesToQueue() + public function testItDelegatesMessagesToQueue(): void { $message = new PlainMessage('SendNewsletter'); @@ -43,7 +45,7 @@ public function testItDelegatesMessagesToQueue() $this->assertSame($message, $envelope->getMessage()); } - public function testItUsesGivenQueueName() + public function testItUsesGivenQueueName(): void { $message = new PlainMessage('SendNewsletter'); diff --git a/tests/Queue/AbstractQueueTest.php b/tests/Queue/AbstractQueueTest.php index 6657b685..5a9e9f2e 100644 --- a/tests/Queue/AbstractQueueTest.php +++ b/tests/Queue/AbstractQueueTest.php @@ -1,5 +1,7 @@ expectException(\Bernard\Exception\InvalidOperationException::class); $this->expectExceptionMessage('Queue "send-newsletter" is closed.'); @@ -17,10 +19,10 @@ public function testNotAllowedWhenClosed($method, array $arguments = []) $queue = $this->createQueue('send-newsletter'); $queue->close(); - call_user_func_array([$queue, $method], $arguments); + \call_user_func_array([$queue, $method], $arguments); } - public function testNameAsToString() + public function testNameAsToString(): void { $queue = $this->createQueue('long-name'); diff --git a/tests/Queue/InMemoryQueueTest.php b/tests/Queue/InMemoryQueueTest.php index d52a5ff3..505bce94 100644 --- a/tests/Queue/InMemoryQueueTest.php +++ b/tests/Queue/InMemoryQueueTest.php @@ -1,5 +1,7 @@ createMock('Bernard\Message')); @@ -20,7 +22,7 @@ public function testDequeue() $this->assertNull($queue->dequeue()); } - public function testPeek() + public function testPeek(): void { $queue = new InMemoryQueue('send-newsletter'); diff --git a/tests/Queue/PersistentQueueTest.php b/tests/Queue/PersistentQueueTest.php index 792817d4..cbb47391 100644 --- a/tests/Queue/PersistentQueueTest.php +++ b/tests/Queue/PersistentQueueTest.php @@ -1,5 +1,7 @@ driver = $this->createMock('Bernard\Driver'); $this->serializer = $this->createMock('Bernard\Serializer'); } - public function testEnqueue() + public function testEnqueue(): void { $envelope = new Envelope($this->createMock('Bernard\Message')); $this->serializer->expects($this->once())->method('serialize')->with($this->equalTo($envelope)) - ->will($this->returnValue('serialized message')); + ->willReturn('serialized message'); $this->driver->expects($this->once())->method('pushMessage') ->with($this->equalTo('send-newsletter'), $this->equalTo('serialized message')); @@ -26,7 +28,7 @@ public function testEnqueue() $queue->enqueue($envelope); } - public function testAcknowledge() + public function testAcknowledge(): void { $envelope = new Envelope($this->createMock('Bernard\Message')); @@ -34,17 +36,17 @@ public function testAcknowledge() ->with($this->equalTo('send-newsletter'), $this->equalTo('receipt')); $this->driver->expects($this->once())->method('popMessage')->with($this->equalTo('send-newsletter')) - ->will($this->returnValue(new \Bernard\DriverMessage('message', 'receipt'))); + ->willReturn(new \Bernard\DriverMessage('message', 'receipt')); $this->serializer->expects($this->once())->method('unserialize') - ->will($this->returnValue($envelope)); + ->willReturn($envelope); $queue = $this->createQueue('send-newsletter'); $envelope = $queue->dequeue(); $queue->acknowledge($envelope); } - public function testAcknowledgeOnlyIfReceipt() + public function testAcknowledgeOnlyIfReceipt(): void { $envelope = new Envelope($this->createMock('Bernard\Message')); @@ -54,28 +56,28 @@ public function testAcknowledgeOnlyIfReceipt() $queue->acknowledge($envelope); } - public function testCount() + public function testCount(): void { $this->driver->expects($this->once())->method('countMessages')->with($this->equalTo('send-newsletter')) - ->will($this->returnValue(10)); + ->willReturn(10); $queue = $this->createQueue('send-newsletter'); $this->assertEquals(10, $queue->count()); } - public function testDequeue() + public function testDequeue(): void { $messageWrapper = new Envelope($this->createMock('Bernard\Message')); $this->driver->expects($this->at(1))->method('popMessage')->with($this->equalTo('send-newsletter')) - ->will($this->returnValue(new \Bernard\DriverMessage('serialized', null))); + ->willReturn(new \Bernard\DriverMessage('serialized', null)); $this->driver->expects($this->at(2))->method('popMessage')->with($this->equalTo('send-newsletter')) - ->will($this->returnValue(null)); + ->willReturn(null); $this->serializer->expects($this->once())->method('unserialize')->with($this->equalTo('serialized')) - ->will($this->returnValue($messageWrapper)); + ->willReturn($messageWrapper); $queue = $this->createQueue('send-newsletter'); @@ -86,14 +88,14 @@ public function testDequeue() /** * @dataProvider peekDataProvider */ - public function testPeekDserializesMessages($index, $limit) + public function testPeekDserializesMessages($index, $limit): void { $this->serializer->expects($this->at(0))->method('unserialize')->with($this->equalTo('message1')); $this->serializer->expects($this->at(1))->method('unserialize')->with($this->equalTo('message2')); $this->serializer->expects($this->at(2))->method('unserialize')->with($this->equalTo('message3')); $this->driver->expects($this->once())->method('peekQueue')->with($this->equalTo('send-newsletter'), $this->equalTo($index), $this->equalTo($limit)) - ->will($this->returnValue(['message1', 'message2', 'message3'])); + ->willReturn(['message1', 'message2', 'message3']); $queue = $this->createQueue('send-newsletter'); $queue->peek($index, $limit); diff --git a/tests/Queue/RoundRobinQueueTest.php b/tests/Queue/RoundRobinQueueTest.php index 1d7065a7..6fdd6b7b 100644 --- a/tests/Queue/RoundRobinQueueTest.php +++ b/tests/Queue/RoundRobinQueueTest.php @@ -1,5 +1,7 @@ queues = [ new InMemoryQueue('1'), @@ -30,7 +32,7 @@ public function setUp(): void $this->round = new RoundRobinQueue($this->queues); } - public function testEnqueueWithUnrecognizedQueue() + public function testEnqueueWithUnrecognizedQueue(): void { $this->expectException(\DomainException::class); $this->expectExceptionMessage('Unrecognized queue specified: foo'); @@ -38,19 +40,19 @@ public function testEnqueueWithUnrecognizedQueue() $this->round->enqueue($this->getEnvelope('foo')); } - public function testEnqueueWithRecognizedQueue() + public function testEnqueueWithRecognizedQueue(): void { $envelope = $this->getEnvelope('2'); $this->round->enqueue($envelope); $this->assertSame($envelope, $this->round->dequeue()); } - public function testDequeueWithEmptyQueue() + public function testDequeueWithEmptyQueue(): void { $this->assertNull($this->round->dequeue()); } - public function testDequeueRoundRobin() + public function testDequeueRoundRobin(): void { foreach ([ $envelope_1_1 = $this->getEnvelope('1'), @@ -64,7 +66,7 @@ public function testDequeueRoundRobin() $this->assertSame($envelope_1_2, $this->round->dequeue()); } - public function testClose() + public function testClose(): void { $builder = $this->getMockBuilder('Bernard\\Queue\\InMemoryQueue')->setMethods(['close']); $queues = []; @@ -80,7 +82,7 @@ public function testClose() $round->close(); } - public function testPeek() + public function testPeek(): void { foreach ([ $envelope_1_1 = $this->getEnvelope('1'), @@ -92,7 +94,7 @@ public function testPeek() $this->assertSame([$envelope_3_1], $this->round->peek(1, 1)); } - public function testAcknowledgeWithUnrecognizedQueue() + public function testAcknowledgeWithUnrecognizedQueue(): void { $this->expectException(\DomainException::class); $this->expectExceptionMessage('Unrecognized queue specified: foo'); @@ -104,7 +106,7 @@ public function testAcknowledgeWithUnrecognizedQueue() $this->round->acknowledge($dequeued); } - public function testAcknowledgeWithRecognizedQueue() + public function testAcknowledgeWithRecognizedQueue(): void { $builder = $this->getMockBuilder('Bernard\\Queue\\InMemoryQueue')->setMethods(['acknowledge']); $envelope = $this->getEnvelope('2'); @@ -126,7 +128,7 @@ public function testAcknowledgeWithRecognizedQueue() $round->acknowledge($envelope); } - public function testToString() + public function testToString(): void { $this->round->enqueue($this->getEnvelope('1')); $this->round->enqueue($this->getEnvelope('2')); @@ -141,7 +143,7 @@ public function testToString() $this->assertSame('3', (string) $this->round); } - public function testCount() + public function testCount(): void { $this->round->enqueue($this->getEnvelope('1')); $this->round->enqueue($this->getEnvelope('2')); diff --git a/tests/QueueFactory/InMemoryFactoryTest.php b/tests/QueueFactory/InMemoryFactoryTest.php index a473798e..e7ee93b3 100644 --- a/tests/QueueFactory/InMemoryFactoryTest.php +++ b/tests/QueueFactory/InMemoryFactoryTest.php @@ -1,22 +1,24 @@ factory = new InMemoryFactory(); } - public function testImplementsQueueFactory() + public function testImplementsQueueFactory(): void { $this->assertInstanceOf('Bernard\QueueFactory', $this->factory); } - public function testRemoveClosesQueue() + public function testRemoveClosesQueue(): void { $this->expectException(\Bernard\Exception\InvalidOperationException::class); @@ -32,7 +34,7 @@ public function testRemoveClosesQueue() $queue->peek(0, 1); } - public function testItCanCreateQueues() + public function testItCanCreateQueues(): void { $this->assertCount(0, $this->factory); diff --git a/tests/QueueFactory/PersistentFactoryTest.php b/tests/QueueFactory/PersistentFactoryTest.php index 2a7b1396..92bf1204 100644 --- a/tests/QueueFactory/PersistentFactoryTest.php +++ b/tests/QueueFactory/PersistentFactoryTest.php @@ -1,12 +1,14 @@ connection = $this->getMockBuilder('Bernard\Driver') ->disableOriginalConstructor()->getMock(); @@ -14,12 +16,12 @@ public function setUp(): void $this->factory = new PersistentFactory($this->connection, $this->createMock('Bernard\Serializer')); } - public function testImplementsQueueFactory() + public function testImplementsQueueFactory(): void { $this->assertInstanceOf('Bernard\QueueFactory', $this->factory); } - public function testItSavesQueueObjects() + public function testItSavesQueueObjects(): void { $this->connection->expects($this->once())->method('createQueue') ->with($this->equalTo('send-newsletter')); @@ -29,12 +31,12 @@ public function testItSavesQueueObjects() $this->assertSame($queue, $this->factory->create('send-newsletter')); } - public function testRemoveClosesQueue() + public function testRemoveClosesQueue(): void { $this->expectException(\Bernard\Exception\InvalidOperationException::class); $this->connection->expects($this->once())->method('listQueues') - ->will($this->returnValue([])); + ->willReturn([]); $queue = $this->factory->create('send-newsletter'); @@ -46,25 +48,25 @@ public function testRemoveClosesQueue() $queue->peek(0, 1); } - public function testItLazyCreatesQueuesAndAttaches() + public function testItLazyCreatesQueuesAndAttaches(): void { $this->connection->expects($this->once())->method('createQueue')->with($this->equalTo('send-newsletter')); $this->assertInstanceOf('Bernard\Queue\PersistentQueue', $this->factory->create('send-newsletter')); } - public function testItsCountable() + public function testItsCountable(): void { $this->connection->expects($this->once())->method('listQueues') - ->will($this->returnValue(['failed', 'something', 'queue-ness'])); + ->willReturn(['failed', 'something', 'queue-ness']); $this->assertCount(3, $this->factory); } - public function testItGetsAllQueues() + public function testItGetsAllQueues(): void { $this->connection->expects($this->once())->method('listQueues') - ->will($this->returnValue(['queue1', 'queue2'])); + ->willReturn(['queue1', 'queue2']); $all = $this->factory->all(); From 52f337d80da64cc78019a13be9a68d53969d5eb5 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 12:52:46 +0200 Subject: [PATCH 094/108] ci: add php-cs-fixer-check Signed-off-by: Mark Sagi-Kazar --- .github/workflows/static.yaml | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/.github/workflows/static.yaml b/.github/workflows/static.yaml index f20df520..96f5abf8 100644 --- a/.github/workflows/static.yaml +++ b/.github/workflows/static.yaml @@ -13,10 +13,16 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v3 - - name: PHP-CS-Fixer - uses: docker://oskarstark/php-cs-fixer-ga:2.16.6 - continue-on-error: true + - name: Set up Nix + uses: cachix/install-nix-action@v17 with: - args: --dry-run --diff-format udiff + extra_nix_config: | + access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} + + - name: Download dependencies + run: nix develop -c composer update --no-interaction --no-progress + + - name: Run PHP CS Fixer + run: nix develop -c php-cs-fixer fix --diff --dry-run From 090e19b419afffdde0f9a0ddfbaeb713f5387387 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 12:54:49 +0200 Subject: [PATCH 095/108] chore: migrate test config Signed-off-by: Mark Sagi-Kazar --- phpunit.xml.dist | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 6345d7f3..eaffd498 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,22 +1,17 @@ - + + + + + ./src + + - + ./tests/ - - - ./src - - - functional From d1868ebe977e30f2941fd55cb28d8cafeb3c20c4 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 13:00:38 +0200 Subject: [PATCH 096/108] fix: DriverMessage type Signed-off-by: Mark Sagi-Kazar --- src/Driver/PrefetchMessageCache.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Driver/PrefetchMessageCache.php b/src/Driver/PrefetchMessageCache.php index c8aa8f97..84727fca 100644 --- a/src/Driver/PrefetchMessageCache.php +++ b/src/Driver/PrefetchMessageCache.php @@ -14,7 +14,7 @@ final class PrefetchMessageCache /** * Pushes a $message to the bottom of the cache. */ - public function push(string $queueName, essage $message): void + public function push(string $queueName, \Bernard\DriverMessage $message): void { $cache = $this->get($queueName); $cache->enqueue($message); @@ -24,7 +24,7 @@ public function push(string $queueName, essage $message): void * Get the next message in line. Or nothing if there is no more * in the cache. */ - public function pop(string $queueName): ?essage + public function pop(string $queueName): ?\Bernard\DriverMessage { $cache = $this->get($queueName); From 5710d88c975060924b16f3e6ea820446c9a41c2c Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 14:51:57 +0200 Subject: [PATCH 097/108] chore: fix prophecy deprecation Signed-off-by: Mark Sagi-Kazar --- composer.json | 1 + tests/ConsumerTest.php | 2 ++ tests/Driver/Doctrine/ConnectionListenerTest.php | 2 ++ tests/EventListener/LoggerSubscriberTest.php | 2 ++ 4 files changed, 7 insertions(+) diff --git a/composer.json b/composer.json index b202a9e9..06ac44c9 100644 --- a/composer.json +++ b/composer.json @@ -21,6 +21,7 @@ "doctrine/instantiator": "^1.0.5", "friends-of-phpspec/phpspec-code-coverage": "^6.0", "phpspec/phpspec": "^7.0", + "phpspec/prophecy-phpunit": "^2.0", "phpunit/phpunit": "^9.5", "psr/container": "^1.0", "psr/log": "^1.0", diff --git a/tests/ConsumerTest.php b/tests/ConsumerTest.php index 8376649d..7c2b5762 100644 --- a/tests/ConsumerTest.php +++ b/tests/ConsumerTest.php @@ -18,6 +18,8 @@ class ConsumerTest extends \PHPUnit\Framework\TestCase { + use \Prophecy\PhpUnit\ProphecyTrait; + /** * @var Router|ObjectProphecy */ diff --git a/tests/Driver/Doctrine/ConnectionListenerTest.php b/tests/Driver/Doctrine/ConnectionListenerTest.php index 49b20b9c..bf8fe950 100644 --- a/tests/Driver/Doctrine/ConnectionListenerTest.php +++ b/tests/Driver/Doctrine/ConnectionListenerTest.php @@ -9,6 +9,8 @@ class ConnectionListenerTest extends \PHPUnit\Framework\TestCase { + use \Prophecy\PhpUnit\ProphecyTrait; + protected function setUp(): void { $this->connection = $this->prophesize('Doctrine\DBAL\Connection'); diff --git a/tests/EventListener/LoggerSubscriberTest.php b/tests/EventListener/LoggerSubscriberTest.php index cd2b8c57..43f1e2af 100644 --- a/tests/EventListener/LoggerSubscriberTest.php +++ b/tests/EventListener/LoggerSubscriberTest.php @@ -11,6 +11,8 @@ class LoggerSubscriberTest extends \PHPUnit\Framework\TestCase { + use \Prophecy\PhpUnit\ProphecyTrait; + public function testLogsInfoOnProduce(): void { $loggerMock = $this->getMockBuilder(LoggerInterface::class)->getMock(); From eaed2c877589cca9fb036be458ca7232ec40b787 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 14:55:57 +0200 Subject: [PATCH 098/108] chore: fix prefetch message cache Signed-off-by: Mark Sagi-Kazar --- src/Driver/PrefetchMessageCache.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Driver/PrefetchMessageCache.php b/src/Driver/PrefetchMessageCache.php index 84727fca..13ca7226 100644 --- a/src/Driver/PrefetchMessageCache.php +++ b/src/Driver/PrefetchMessageCache.php @@ -4,6 +4,8 @@ namespace Bernard\Driver; +use Bernard\DriverMessage; + /** * @internal */ @@ -14,7 +16,7 @@ final class PrefetchMessageCache /** * Pushes a $message to the bottom of the cache. */ - public function push(string $queueName, \Bernard\DriverMessage $message): void + public function push(string $queueName, DriverMessage $message): void { $cache = $this->get($queueName); $cache->enqueue($message); @@ -24,7 +26,7 @@ public function push(string $queueName, \Bernard\DriverMessage $message): void * Get the next message in line. Or nothing if there is no more * in the cache. */ - public function pop(string $queueName): ?\Bernard\DriverMessage + public function pop(string $queueName): ?DriverMessage { $cache = $this->get($queueName); From b455abfe3952dea84995a83bf8652e5bd9bf6780 Mon Sep 17 00:00:00 2001 From: Mark Sagi-Kazar Date: Wed, 4 May 2022 15:44:06 +0200 Subject: [PATCH 099/108] feat!: relocate DriverMessage to the Driver namespace Signed-off-by: Mark Sagi-Kazar --- src/Driver.php | 2 +- src/Driver/Doctrine/Driver.php | 9 +++++--- src/Driver/FlatFile/Driver.php | 10 +++++---- src/Driver/InMemory/Driver.php | 6 +++-- src/Driver/Message.php | 17 ++++++++++++++ src/Driver/MongoDB/Driver.php | 5 +++-- src/Driver/PrefetchMessageCache.php | 6 ++--- src/DriverMessage.php | 27 ----------------------- tests/Driver/PrefetchMessageCacheTest.php | 2 +- tests/Queue/PersistentQueueTest.php | 4 ++-- 10 files changed, 42 insertions(+), 46 deletions(-) create mode 100644 src/Driver/Message.php delete mode 100644 src/DriverMessage.php diff --git a/src/Driver.php b/src/Driver.php index f0f941b6..2c3bbe58 100644 --- a/src/Driver.php +++ b/src/Driver.php @@ -36,7 +36,7 @@ public function pushMessage(string $queueName, string $message): void; * * If no message is available wait for $duration seconds. */ - public function popMessage(string $queueName, int $duration = 5): ?DriverMessage; + public function popMessage(string $queueName, int $duration = 5): ?Driver\Message; /** * If the driver supports it, this will be called when a message have been successfully processed. diff --git a/src/Driver/Doctrine/Driver.php b/src/Driver/Doctrine/Driver.php index c418b545..8fbbe70d 100644 --- a/src/Driver/Doctrine/Driver.php +++ b/src/Driver/Doctrine/Driver.php @@ -4,6 +4,7 @@ namespace Bernard\Driver\Doctrine; +use Bernard\Driver\Message; use Doctrine\DBAL\Connection; final class Driver implements \Bernard\Driver @@ -52,7 +53,7 @@ public function pushMessage(string $queueName, string $message): void $this->connection->insert('bernard_messages', $data, $types); } - public function popMessage(string $queueName, int $duration = 5): ?\Bernard\DriverMessage + public function popMessage(string $queueName, int $duration = 5): ?Message { $runtime = microtime(true) + $duration; @@ -74,12 +75,14 @@ public function popMessage(string $queueName, int $duration = 5): ?\Bernard\Driv // sleep for 10 ms usleep(10000); } + + return null; } /** * Execute the actual query and process the response. */ - private function doPopMessage(string $queueName): ?\Bernard\DriverMessage + private function doPopMessage(string $queueName): ?Message { $query = 'SELECT id, message FROM bernard_messages WHERE queue = :queue AND visible = :visible @@ -93,7 +96,7 @@ private function doPopMessage(string $queueName): ?\Bernard\DriverMessage if ($id) { $this->connection->update('bernard_messages', ['visible' => 0], compact('id')); - return new \Bernard\DriverMessage($message, $id); + return new Message($message, $id); } } diff --git a/src/Driver/FlatFile/Driver.php b/src/Driver/FlatFile/Driver.php index 6e94b79f..27e94151 100644 --- a/src/Driver/FlatFile/Driver.php +++ b/src/Driver/FlatFile/Driver.php @@ -4,6 +4,8 @@ namespace Bernard\Driver\FlatFile; +use Bernard\Driver\Message; + /** * Flat file driver to provide a simple job queue without any * database. @@ -77,7 +79,7 @@ public function pushMessage(string $queueName, string $message): void chmod($queueDir.\DIRECTORY_SEPARATOR.$filename, $this->permissions); } - public function popMessage(string $queueName, int $duration = 5): ?\Bernard\DriverMessage + public function popMessage(string $queueName, int $duration = 5): ?Message { $runtime = microtime(true) + $duration; $queueDir = $this->getQueueDirectory($queueName); @@ -88,7 +90,7 @@ public function popMessage(string $queueName, int $duration = 5): ?\Bernard\Driv if ($files) { $id = array_pop($files); if (@rename($queueDir.\DIRECTORY_SEPARATOR.$id, $queueDir.\DIRECTORY_SEPARATOR.$id.'.proceed')) { - return new \Bernard\DriverMessage(file_get_contents($queueDir.\DIRECTORY_SEPARATOR.$id.'.proceed'), $id); + return new Message(file_get_contents($queueDir.\DIRECTORY_SEPARATOR.$id.'.proceed'), $id); } return $this->processFileOrFail($queueDir, $id); @@ -101,7 +103,7 @@ public function popMessage(string $queueName, int $duration = 5): ?\Bernard\Driv } } - private function processFileOrFail(string $queueDir, string $id): \Bernard\DriverMessage + private function processFileOrFail(string $queueDir, string $id): Message { $name = $queueDir.\DIRECTORY_SEPARATOR.$id; $newName = $name.'.proceed'; @@ -110,7 +112,7 @@ private function processFileOrFail(string $queueDir, string $id): \Bernard\Drive throw new InsufficientPermissionsException('Unable to process file: '.$name); } - return new \Bernard\DriverMessage(file_get_contents($newName), $id); + return new Message(file_get_contents($newName), $id); } public function acknowledgeMessage(string $queueName, mixed $receipt): void diff --git a/src/Driver/InMemory/Driver.php b/src/Driver/InMemory/Driver.php index 6683cc26..ebbd8cac 100644 --- a/src/Driver/InMemory/Driver.php +++ b/src/Driver/InMemory/Driver.php @@ -4,6 +4,8 @@ namespace Bernard\Driver\InMemory; +use Bernard\Driver\Message; + /** * @author Márk Sági-Kazár */ @@ -35,13 +37,13 @@ public function pushMessage(string $queueName, string $message): void $this->queues[$queueName][] = $message; } - public function popMessage(string $queueName, int $duration = 5): ?\Bernard\DriverMessage + public function popMessage(string $queueName, int $duration = 5): ?Message { if (!\array_key_exists($queueName, $this->queues) || \count($this->queues[$queueName]) < 1) { return null; } - return new \Bernard\DriverMessage(array_shift($this->queues[$queueName])); + return new Message(array_shift($this->queues[$queueName])); } public function acknowledgeMessage(string $queueName, mixed $receipt): void diff --git a/src/Driver/Message.php b/src/Driver/Message.php new file mode 100644 index 00000000..5e05c647 --- /dev/null +++ b/src/Driver/Message.php @@ -0,0 +1,17 @@ +messages->insert($data); } - public function popMessage(string $queueName, int $duration = 5): ?\Bernard\DriverMessage + public function popMessage(string $queueName, int $duration = 5): ?Message { $runtime = microtime(true) + $duration; @@ -63,7 +64,7 @@ public function popMessage(string $queueName, int $duration = 5): ?\Bernard\Driv ); if ($result) { - return new \Bernard\DriverMessage((string) $result['message'], (string) $result['_id']); + return new Message((string) $result['message'], (string) $result['_id']); } usleep(10000); diff --git a/src/Driver/PrefetchMessageCache.php b/src/Driver/PrefetchMessageCache.php index 13ca7226..113d3814 100644 --- a/src/Driver/PrefetchMessageCache.php +++ b/src/Driver/PrefetchMessageCache.php @@ -4,8 +4,6 @@ namespace Bernard\Driver; -use Bernard\DriverMessage; - /** * @internal */ @@ -16,7 +14,7 @@ final class PrefetchMessageCache /** * Pushes a $message to the bottom of the cache. */ - public function push(string $queueName, DriverMessage $message): void + public function push(string $queueName, Message $message): void { $cache = $this->get($queueName); $cache->enqueue($message); @@ -26,7 +24,7 @@ public function push(string $queueName, DriverMessage $message): void * Get the next message in line. Or nothing if there is no more * in the cache. */ - public function pop(string $queueName): ?DriverMessage + public function pop(string $queueName): ?Message { $cache = $this->get($queueName); diff --git a/src/DriverMessage.php b/src/DriverMessage.php deleted file mode 100644 index 591775cb..00000000 --- a/src/DriverMessage.php +++ /dev/null @@ -1,27 +0,0 @@ -message = $message; - $this->receipt = $receipt; - } -} diff --git a/tests/Driver/PrefetchMessageCacheTest.php b/tests/Driver/PrefetchMessageCacheTest.php index 17db97ec..93a595a5 100644 --- a/tests/Driver/PrefetchMessageCacheTest.php +++ b/tests/Driver/PrefetchMessageCacheTest.php @@ -10,7 +10,7 @@ class PrefetchMessageCacheTest extends \PHPUnit\Framework\TestCase { public function testPushesAndPop(): void { - $driverMessage = new \Bernard\DriverMessage('message1', 'r0'); + $driverMessage = new \Bernard\Driver\Message('message1', 'r0'); $cache = new PrefetchMessageCache(); $cache->push('my-queue', $driverMessage); diff --git a/tests/Queue/PersistentQueueTest.php b/tests/Queue/PersistentQueueTest.php index cbb47391..f91dffca 100644 --- a/tests/Queue/PersistentQueueTest.php +++ b/tests/Queue/PersistentQueueTest.php @@ -36,7 +36,7 @@ public function testAcknowledge(): void ->with($this->equalTo('send-newsletter'), $this->equalTo('receipt')); $this->driver->expects($this->once())->method('popMessage')->with($this->equalTo('send-newsletter')) - ->willReturn(new \Bernard\DriverMessage('message', 'receipt')); + ->willReturn(new \Bernard\Driver\Message('message', 'receipt')); $this->serializer->expects($this->once())->method('unserialize') ->willReturn($envelope); @@ -71,7 +71,7 @@ public function testDequeue(): void $messageWrapper = new Envelope($this->createMock('Bernard\Message')); $this->driver->expects($this->at(1))->method('popMessage')->with($this->equalTo('send-newsletter')) - ->willReturn(new \Bernard\DriverMessage('serialized', null)); + ->willReturn(new \Bernard\Driver\Message('serialized', null)); $this->driver->expects($this->at(2))->method('popMessage')->with($this->equalTo('send-newsletter')) ->willReturn(null); From 5266e5206e9f47553e673a365400181179abfce5 Mon Sep 17 00:00:00 2001 From: Eduardo Scarello Date: Tue, 4 Feb 2025 19:53:07 -0300 Subject: [PATCH 100/108] Fix some return types --- src/Driver/Delayable/DelayablePheanstalkDriver.php | 4 ++-- src/Queue/PersistentQueue.php | 2 +- tests/Driver/Delayable/DelayablePheanstalkDriverTest.php | 4 ++-- tests/EnvelopeTest.php | 6 +++--- tests/Queue/PersistentQueueTest.php | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Driver/Delayable/DelayablePheanstalkDriver.php b/src/Driver/Delayable/DelayablePheanstalkDriver.php index 33686cd5..119994d2 100644 --- a/src/Driver/Delayable/DelayablePheanstalkDriver.php +++ b/src/Driver/Delayable/DelayablePheanstalkDriver.php @@ -16,7 +16,7 @@ class DelayablePheanstalkDriver extends PheanstalkDriver implements DelayableDri /** * {@inheritDoc} */ - public function pushMessageWithDelay($queueName, $message, $delay) + public function pushMessageWithDelay($queueName, $message, $delay): void { $this->pheanstalk->putInTube( $queueName, @@ -25,4 +25,4 @@ public function pushMessageWithDelay($queueName, $message, $delay) (int) $delay ); } -} \ No newline at end of file +} diff --git a/src/Queue/PersistentQueue.php b/src/Queue/PersistentQueue.php index 40b76d5c..6244e92b 100644 --- a/src/Queue/PersistentQueue.php +++ b/src/Queue/PersistentQueue.php @@ -79,7 +79,7 @@ public function enqueue(Envelope $envelope): void } } - private function assertDriverIsDelayable() + private function assertDriverIsDelayable(): void { if (!($this->driver instanceof DelayableDriver)) { throw new InvalidOperationException('This driver can\'t manage delayed messages'); diff --git a/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php b/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php index eee05e3c..3aea1b3b 100644 --- a/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php +++ b/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php @@ -7,7 +7,7 @@ class DelayablePheanstalkDriverTest extends TestCase { - public function setUp() + public function setUp(): void { $this->pheanstalk = $this->getMockBuilder('Pheanstalk\Pheanstalk') ->setMethods(array( @@ -19,7 +19,7 @@ public function setUp() $this->driver = new DelayablePheanstalkDriver($this->pheanstalk); } - public function testItPushesMessagesWithDelay() + public function testItPushesMessagesWithDelay(): void { $this->pheanstalk ->expects($this->once()) diff --git a/tests/EnvelopeTest.php b/tests/EnvelopeTest.php index a3379cc4..c979fb8b 100644 --- a/tests/EnvelopeTest.php +++ b/tests/EnvelopeTest.php @@ -19,14 +19,14 @@ public function testItWrapsAMessageWithMetadata(): void $this->assertSame($message, $envelope->getMessage()); } - public function testNotDelayedMetadata() + public function testNotDelayedMetadata(): void { $envelope = new Envelope($message = new PlainMessage('SendNewsletter')); $this->assertFalse($envelope->isDelayed()); $this->assertEquals(0, $envelope->getDelay()); } - public function testDelayedMetadata() + public function testDelayedMetadata(): void { $envelope = new Envelope($message = new PlainMessage('SendNewsletter'), 10); $this->assertTrue($envelope->isDelayed()); @@ -37,7 +37,7 @@ public function testDelayedMetadata() * @expectedException Bernard\Exception\InvalidOperationException * @expectedExceptionMessage Delay must be greater or equal than zero */ - public function testNegativeDelay() + public function testNegativeDelay(): void { $envelope = new Envelope($message = new PlainMessage('SendNewsletter'), -10); } diff --git a/tests/Queue/PersistentQueueTest.php b/tests/Queue/PersistentQueueTest.php index 90c1bad0..ee2a1867 100644 --- a/tests/Queue/PersistentQueueTest.php +++ b/tests/Queue/PersistentQueueTest.php @@ -127,7 +127,7 @@ protected function createQueue($name) * @expectedException Bernard\Exception\InvalidOperationException * @expectedExceptionMessage This driver can't manage delayed messages */ - public function testEnqueueDelayedWithNotDelayableDriver() + public function testEnqueueDelayedWithNotDelayableDriver(): void { $envelope = new Envelope($this->createMock('Bernard\Message'), 10); @@ -135,7 +135,7 @@ public function testEnqueueDelayedWithNotDelayableDriver() $queue->enqueue($envelope); } - public function testEnqueueDelayed() + public function testEnqueueDelayed(): void { $this->driver = $this->createMock('Bernard\DelayableDriver'); $envelope = new Envelope($this->createMock('Bernard\Message'), 10); From d9bbdf898ea1856331b3d0a57e0574837bb5c6de Mon Sep 17 00:00:00 2001 From: Eduardo Scarello Date: Wed, 5 Feb 2025 12:14:16 -0300 Subject: [PATCH 101/108] Copy pheanstalk driver for testing --- src/DelayableDriver.php | 4 +- .../Delayable/DelayablePheanstalkDriver.php | 4 +- src/Driver/Pheanstalk/Driver.php | 64 +++++++++++++++++++ src/Event/EnvelopeEvent.php | 3 +- src/Event/PingEvent.php | 2 +- 5 files changed, 71 insertions(+), 6 deletions(-) create mode 100644 src/Driver/Pheanstalk/Driver.php diff --git a/src/DelayableDriver.php b/src/DelayableDriver.php index 0787ccf2..0775219e 100644 --- a/src/DelayableDriver.php +++ b/src/DelayableDriver.php @@ -14,5 +14,5 @@ interface DelayableDriver extends Driver * @param string $message * @param int $delay Delay in seconds */ - public function pushMessageWithDelay($queueName, $message, $delay); -} \ No newline at end of file + public function pushMessageWithDelay($queueName, $message, $delay): void; +} diff --git a/src/Driver/Delayable/DelayablePheanstalkDriver.php b/src/Driver/Delayable/DelayablePheanstalkDriver.php index 119994d2..d5f43b5f 100644 --- a/src/Driver/Delayable/DelayablePheanstalkDriver.php +++ b/src/Driver/Delayable/DelayablePheanstalkDriver.php @@ -1,7 +1,7 @@ */ -class DelayablePheanstalkDriver extends PheanstalkDriver implements DelayableDriver +class DelayablePheanstalkDriver extends Pheanstalk\Driver implements DelayableDriver { /** * {@inheritDoc} diff --git a/src/Driver/Pheanstalk/Driver.php b/src/Driver/Pheanstalk/Driver.php new file mode 100644 index 00000000..3ee8cbbf --- /dev/null +++ b/src/Driver/Pheanstalk/Driver.php @@ -0,0 +1,64 @@ +pheanstalk->listTubes(); + } + + public function createQueue(string $queueName): void + { + } + + public function removeQueue(string $queueName): void + { + } + + public function pushMessage(string $queueName, string $message): void + { + $this->pheanstalk->useTube($queueName)->put($message); + } + + public function popMessage(string $queueName, int $duration = 5): ?Message + { + if ($job = $this->pheanstalk->watchOnly($queueName)->reserveFromTube($queueName, $duration)) { + return new Message($job->getData(), $job); + } + + return null; + } + + public function acknowledgeMessage(string $queueName, mixed $receipt): void + { + $this->pheanstalk->delete($receipt); + } + + public function info(): array + { + return iterator_to_array($this->pheanstalk->stats()); + } + + public function countMessages(string $queueName): int + { + $stats = $this->pheanstalk->statsTube($queueName); + + return (int) $stats['current-jobs-ready']; + } + + public function peekQueue(string $queueName, int $index = 0, int $limit = 20): array + { + return []; + } +} diff --git a/src/Event/EnvelopeEvent.php b/src/Event/EnvelopeEvent.php index 68ca2ed1..e3bef932 100644 --- a/src/Event/EnvelopeEvent.php +++ b/src/Event/EnvelopeEvent.php @@ -6,8 +6,9 @@ use Bernard\Envelope; use Bernard\Queue; +use Symfony\Contracts\EventDispatcher\Event; -class EnvelopeEvent extends \Symfony\Component\EventDispatcher\Event +class EnvelopeEvent extends Event { protected $envelope; protected $queue; diff --git a/src/Event/PingEvent.php b/src/Event/PingEvent.php index e1d2a663..0c3d8dff 100644 --- a/src/Event/PingEvent.php +++ b/src/Event/PingEvent.php @@ -5,7 +5,7 @@ namespace Bernard\Event; use Bernard\Queue; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; class PingEvent extends Event { From 81f309b8089c96cf151544aba0715a2e81c662cb Mon Sep 17 00:00:00 2001 From: Eduardo Scarello Date: Wed, 5 Feb 2025 15:44:23 -0300 Subject: [PATCH 102/108] Fixes from uts --- composer.json | 7 ++++--- src/Command/ConsumeCommand.php | 4 +++- src/Command/ProduceCommand.php | 4 +++- src/Driver/Delayable/DelayablePheanstalkDriver.php | 4 +++- src/Driver/Doctrine/Command/AbstractCommand.php | 6 ++++-- src/Envelope.php | 2 +- tests/ConsumerTest.php | 3 ++- .../Driver/Delayable/DelayablePheanstalkDriverTest.php | 4 ++-- tests/Driver/Doctrine/ConnectionListenerTest.php | 3 ++- tests/EnvelopeTest.php | 10 +++++----- tests/Event/EnvelopeEventTest.php | 3 ++- tests/EventListener/LoggerSubscriberTest.php | 3 ++- tests/ProducerTest.php | 2 +- tests/Queue/PersistentQueueTest.php | 8 ++++---- 14 files changed, 38 insertions(+), 25 deletions(-) diff --git a/composer.json b/composer.json index 06ac44c9..89ebd43d 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,8 @@ "php": ">=8.0", "beberlei/assert": "^2.1 || ^3.0", "bernard/normalt": "^1.0", - "symfony/event-dispatcher": "^3.0 || ^4.0" + "symfony/event-dispatcher": "v6.0.19", + "symfony/event-dispatcher-contracts": "^2" }, "require-dev": { "doctrine/dbal": "^2.5", @@ -22,10 +23,10 @@ "friends-of-phpspec/phpspec-code-coverage": "^6.0", "phpspec/phpspec": "^7.0", "phpspec/prophecy-phpunit": "^2.0", - "phpunit/phpunit": "^9.5", + "phpunit/phpunit": "^9.3", "psr/container": "^1.0", "psr/log": "^1.0", - "symfony/console": "^3.0 || ^4.0" + "symfony/console": "v6.0.19" }, "suggest": { "doctrine/dbal": "Allow sending messages to simulated message queue in a database via doctrine dbal", diff --git a/src/Command/ConsumeCommand.php b/src/Command/ConsumeCommand.php index fc948ff3..29d1bedb 100644 --- a/src/Command/ConsumeCommand.php +++ b/src/Command/ConsumeCommand.php @@ -43,11 +43,13 @@ public function configure(): void /** * {@inheritdoc} */ - public function execute(InputInterface $input, OutputInterface $output): void + public function execute(InputInterface $input, OutputInterface $output): int { $queue = $this->getQueue($input->getArgument('queue')); $this->consumer->consume($queue, $input->getOptions()); + + return self::SUCCESS; } /** diff --git a/src/Command/ProduceCommand.php b/src/Command/ProduceCommand.php index 8de4b2dc..86aee2b0 100644 --- a/src/Command/ProduceCommand.php +++ b/src/Command/ProduceCommand.php @@ -37,7 +37,7 @@ public function configure(): void /** * {@inheritdoc} */ - public function execute(InputInterface $input, OutputInterface $output): void + public function execute(InputInterface $input, OutputInterface $output): int { $name = $input->getArgument('name'); $queue = $input->getOption('queue'); @@ -52,5 +52,7 @@ public function execute(InputInterface $input, OutputInterface $output): void } $this->producer->produce(new PlainMessage($name, $message), $queue); + + return self::SUCCESS; } } diff --git a/src/Driver/Delayable/DelayablePheanstalkDriver.php b/src/Driver/Delayable/DelayablePheanstalkDriver.php index d5f43b5f..09a8b012 100644 --- a/src/Driver/Delayable/DelayablePheanstalkDriver.php +++ b/src/Driver/Delayable/DelayablePheanstalkDriver.php @@ -13,6 +13,8 @@ */ class DelayablePheanstalkDriver extends Pheanstalk\Driver implements DelayableDriver { + public const DEFAULT_PRIORITY = 1024; // most urgent: 0, least urgent: 4294967295 + /** * {@inheritDoc} */ @@ -21,7 +23,7 @@ public function pushMessageWithDelay($queueName, $message, $delay): void $this->pheanstalk->putInTube( $queueName, $message, - PheanstalkInterface::DEFAULT_PRIORITY, + self::DEFAULT_PRIORITY, (int) $delay ); } diff --git a/src/Driver/Doctrine/Command/AbstractCommand.php b/src/Driver/Doctrine/Command/AbstractCommand.php index ef2e1b3c..2bb2b78a 100644 --- a/src/Driver/Doctrine/Command/AbstractCommand.php +++ b/src/Driver/Doctrine/Command/AbstractCommand.php @@ -31,7 +31,7 @@ public function configure(): void /** * {@inheritdoc} */ - public function execute(InputInterface $input, OutputInterface $output): void + public function execute(InputInterface $input, OutputInterface $output): int { $schema = new Schema(); MessagesSchema::create($schema); @@ -40,13 +40,15 @@ public function execute(InputInterface $input, OutputInterface $output): void if ($input->getOption('dump-sql')) { $output->writeln(implode(';'.\PHP_EOL, $this->getSql($sync, $schema)).';'); - return; + return self::SUCCESS; } $output->writeln('ATTENTION: This operation should not be executed in a production environment.'.\PHP_EOL); $output->writeln('Applying database schema changes...'); $this->applySql($sync, $schema); $output->writeln('Schema changes applied successfully!'); + + return self::SUCCESS; } /** diff --git a/src/Envelope.php b/src/Envelope.php index ea4c5563..767a8f3f 100644 --- a/src/Envelope.php +++ b/src/Envelope.php @@ -26,7 +26,7 @@ public function __construct(Message $message, int $delay = 0) $this->message = $message; $this->delay = $delay; - $this->class = $message::class; + $this->class = get_class($message); $this->timestamp = time(); } diff --git a/tests/ConsumerTest.php b/tests/ConsumerTest.php index 6d43c53d..fc0b0ff7 100644 --- a/tests/ConsumerTest.php +++ b/tests/ConsumerTest.php @@ -14,11 +14,12 @@ use Bernard\Queue\InMemoryQueue; use Bernard\Receiver; use Bernard\Router; +use Prophecy\PhpUnit\ProphecyTrait; use Prophecy\Prophecy\ObjectProphecy; class ConsumerTest extends \PHPUnit\Framework\TestCase { - use \Prophecy\PhpUnit\ProphecyTrait; + use ProphecyTrait; /** * @var Router|ObjectProphecy diff --git a/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php b/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php index 3aea1b3b..a6891762 100644 --- a/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php +++ b/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php @@ -9,7 +9,7 @@ class DelayablePheanstalkDriverTest extends TestCase { public function setUp(): void { - $this->pheanstalk = $this->getMockBuilder('Pheanstalk\Pheanstalk') + $this->pheanstalk = $this->getMockBuilder('Pheanstalk\PheanstalkInterface') ->setMethods(array( 'putInTube' )) @@ -27,7 +27,7 @@ public function testItPushesMessagesWithDelay(): void ->with( $this->equalTo('my-queue'), $this->equalTo('This is a message'), - $this->equalTo(PheanstalkInterface::DEFAULT_PRIORITY), + $this->equalTo(DelayablePheanstalkDriver::DEFAULT_PRIORITY), $this->equalTo(10) ); diff --git a/tests/Driver/Doctrine/ConnectionListenerTest.php b/tests/Driver/Doctrine/ConnectionListenerTest.php index bf8fe950..de96b4c2 100644 --- a/tests/Driver/Doctrine/ConnectionListenerTest.php +++ b/tests/Driver/Doctrine/ConnectionListenerTest.php @@ -6,10 +6,11 @@ use Bernard\Driver\Doctrine\ConnectionListener; use Doctrine\DBAL\DBALException; +use Prophecy\PhpUnit\ProphecyTrait; class ConnectionListenerTest extends \PHPUnit\Framework\TestCase { - use \Prophecy\PhpUnit\ProphecyTrait; + use ProphecyTrait; protected function setUp(): void { diff --git a/tests/EnvelopeTest.php b/tests/EnvelopeTest.php index c979fb8b..5fc8d63b 100644 --- a/tests/EnvelopeTest.php +++ b/tests/EnvelopeTest.php @@ -4,6 +4,7 @@ namespace Bernard\Tests; +use Bernard\Exception\InvalidOperationException; use Bernard\Message\PlainMessage; use Bernard\Envelope; @@ -33,12 +34,11 @@ public function testDelayedMetadata(): void $this->assertEquals(10, $envelope->getDelay()); } - /** - * @expectedException Bernard\Exception\InvalidOperationException - * @expectedExceptionMessage Delay must be greater or equal than zero - */ public function testNegativeDelay(): void { - $envelope = new Envelope($message = new PlainMessage('SendNewsletter'), -10); + $this->expectException(InvalidOperationException::class); + $this->expectExceptionMessage('Delay must be greater or equal than zero'); + + new Envelope(new PlainMessage('SendNewsletter'), -10); } } diff --git a/tests/Event/EnvelopeEventTest.php b/tests/Event/EnvelopeEventTest.php index dd853997..6583eb22 100644 --- a/tests/Event/EnvelopeEventTest.php +++ b/tests/Event/EnvelopeEventTest.php @@ -7,6 +7,7 @@ use Bernard\Envelope; use Bernard\Event\EnvelopeEvent; use Bernard\Message; +use Symfony\Contracts\EventDispatcher\Event; class EnvelopeEventTest extends \PHPUnit\Framework\TestCase { @@ -20,7 +21,7 @@ protected function setUp(): void public function testIsEvent(): void { - $this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', new EnvelopeEvent($this->envelope, $this->queue)); + $this->assertInstanceOf(Event::class, new EnvelopeEvent($this->envelope, $this->queue)); } public function hasEnvelopeAndQueue(): void diff --git a/tests/EventListener/LoggerSubscriberTest.php b/tests/EventListener/LoggerSubscriberTest.php index 43f1e2af..a0a7c557 100644 --- a/tests/EventListener/LoggerSubscriberTest.php +++ b/tests/EventListener/LoggerSubscriberTest.php @@ -7,11 +7,12 @@ use Bernard\Event\EnvelopeEvent; use Bernard\Event\RejectEnvelopeEvent; use Bernard\EventListener\LoggerSubscriber; +use Prophecy\PhpUnit\ProphecyTrait; use Psr\Log\LoggerInterface; class LoggerSubscriberTest extends \PHPUnit\Framework\TestCase { - use \Prophecy\PhpUnit\ProphecyTrait; + use ProphecyTrait; public function testLogsInfoOnProduce(): void { diff --git a/tests/ProducerTest.php b/tests/ProducerTest.php index fb876f59..37a87a2b 100644 --- a/tests/ProducerTest.php +++ b/tests/ProducerTest.php @@ -58,7 +58,7 @@ public function testItUsesGivenQueueName(): void public function testWithDelay() { - $message = new DefaultMessage('SendNewsletter'); + $message = new PlainMessage('SendNewsletter'); $this->producer->produce($message, null, 10); diff --git a/tests/Queue/PersistentQueueTest.php b/tests/Queue/PersistentQueueTest.php index ee2a1867..d6ac7f2a 100644 --- a/tests/Queue/PersistentQueueTest.php +++ b/tests/Queue/PersistentQueueTest.php @@ -5,6 +5,7 @@ namespace Bernard\Tests\Queue; use Bernard\Envelope; +use Bernard\Exception\InvalidOperationException; use Bernard\Queue\PersistentQueue; class PersistentQueueTest extends AbstractQueueTest @@ -123,12 +124,11 @@ protected function createQueue($name) return new PersistentQueue($name, $this->driver, $this->serializer); } - /** - * @expectedException Bernard\Exception\InvalidOperationException - * @expectedExceptionMessage This driver can't manage delayed messages - */ public function testEnqueueDelayedWithNotDelayableDriver(): void { + $this->expectException(InvalidOperationException::class); + $this->expectExceptionMessage('This driver can\'t manage delayed messages'); + $envelope = new Envelope($this->createMock('Bernard\Message'), 10); $queue = $this->createQueue('send-newsletter'); From 19d648fb8e0f2e8d376f9e897c922c957c00ee2b Mon Sep 17 00:00:00 2001 From: Eduardo Scarello Date: Wed, 5 Feb 2025 15:57:35 -0300 Subject: [PATCH 103/108] Try 8.3 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index bd8d97c6..87fda681 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -38,7 +38,7 @@ jobs: strategy: max-parallel: 10 matrix: - php: ['8.0', '8.1'] + php: [ '8.0', '8.1', '8.3' ] steps: - name: Set up PHP From d362b3afeeb7015e6e253f497a9d4a5c3a3130c7 Mon Sep 17 00:00:00 2001 From: Eduardo Scarello Date: Thu, 6 Feb 2025 15:19:58 -0300 Subject: [PATCH 104/108] Fixes php-cs-fixer --- .php-cs-fixer.dist.php | 1 + src/DelayableDriver.php | 11 ++++++----- src/Driver/Delayable/DelayablePheanstalkDriver.php | 7 ++++--- src/Envelope.php | 9 +++------ src/Producer.php | 8 +------- src/Queue/PersistentQueue.php | 4 ++-- src/QueueFactory/PersistentFactory.php | 5 +---- tests/ConsumerTest.php | 4 ++-- .../Delayable/DelayablePheanstalkDriverTest.php | 9 +++++---- tests/EnvelopeTest.php | 2 +- tests/ProducerTest.php | 2 +- tests/Queue/PersistentQueueTest.php | 2 +- tests/QueueFactory/PersistentFactoryTest.php | 2 +- 13 files changed, 29 insertions(+), 37 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 7aeb6849..4d1935a1 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -19,3 +19,4 @@ ); return $config; + diff --git a/src/DelayableDriver.php b/src/DelayableDriver.php index 0775219e..529cccb8 100644 --- a/src/DelayableDriver.php +++ b/src/DelayableDriver.php @@ -1,18 +1,19 @@ */ interface DelayableDriver extends Driver { /** - * Insert a message with delay + * Insert a message with delay. * - * @param string $queueName - * @param string $message - * @param int $delay Delay in seconds + * @param string $queueName + * @param string $message + * @param int $delay Delay in seconds */ public function pushMessageWithDelay($queueName, $message, $delay): void; } diff --git a/src/Driver/Delayable/DelayablePheanstalkDriver.php b/src/Driver/Delayable/DelayablePheanstalkDriver.php index 09a8b012..01a9b8b5 100644 --- a/src/Driver/Delayable/DelayablePheanstalkDriver.php +++ b/src/Driver/Delayable/DelayablePheanstalkDriver.php @@ -1,12 +1,13 @@ diff --git a/src/Envelope.php b/src/Envelope.php index 767a8f3f..21949457 100644 --- a/src/Envelope.php +++ b/src/Envelope.php @@ -26,7 +26,7 @@ public function __construct(Message $message, int $delay = 0) $this->message = $message; $this->delay = $delay; - $this->class = get_class($message); + $this->class = $message::class; $this->timestamp = time(); } @@ -38,12 +38,9 @@ public function getMessage() return $this->message; } - /** - * @return bool - */ - public function isDelayed() + public function isDelayed(): bool { - return ($this->delay > 0); + return $this->delay > 0; } /** diff --git a/src/Producer.php b/src/Producer.php index 9a14bb49..05d63bab 100644 --- a/src/Producer.php +++ b/src/Producer.php @@ -20,7 +20,7 @@ public function __construct(QueueFactory $queues, EventDispatcherInterface $disp /** * @param string|null $queueName - * @param int $delay Delay (in seconds) + * @param int $delay Delay (in seconds) */ public function produce(Message $message, $queueName = null, int $delay = 0): void { @@ -29,17 +29,11 @@ public function produce(Message $message, $queueName = null, int $delay = 0): vo $queue = $this->queues->create($queueName); $queue->enqueue($envelope = new Envelope($message, $delay)); - $this->dispatcher->dispatch(new EnvelopeEvent($envelope, $queue), BernardEvents::PRODUCE); } private function dispatch($eventName, EnvelopeEvent $event): void { $this->dispatcher->dispatch($event, $eventName); - - // TODO see this shitty if -// $this->dispatcher instanceof \Symfony\Contracts\EventDispatcher\EventDispatcherInterface -// ? $this->dispatcher->dispatch($event, $eventName) -// : $this->dispatcher->dispatch($eventName, $event); } } diff --git a/src/Queue/PersistentQueue.php b/src/Queue/PersistentQueue.php index 6244e92b..a076874e 100644 --- a/src/Queue/PersistentQueue.php +++ b/src/Queue/PersistentQueue.php @@ -4,11 +4,11 @@ namespace Bernard\Queue; -use Bernard\Driver; use Bernard\DelayableDriver; +use Bernard\Driver; use Bernard\Envelope; -use Bernard\Serializer; use Bernard\Exception\InvalidOperationException; +use Bernard\Serializer; class PersistentQueue extends AbstractQueue { diff --git a/src/QueueFactory/PersistentFactory.php b/src/QueueFactory/PersistentFactory.php index fb24bf95..754c8fb3 100644 --- a/src/QueueFactory/PersistentFactory.php +++ b/src/QueueFactory/PersistentFactory.php @@ -58,12 +58,9 @@ public function exists($queueName) return isset($this->queues[$queueName]) ?: \in_array($queueName, $this->driver->listQueues()); } - /** - * @return int - */ public function count(): int { - return count($this->driver->listQueues()); + return \count($this->driver->listQueues()); } /** diff --git a/tests/ConsumerTest.php b/tests/ConsumerTest.php index fc0b0ff7..00e93795 100644 --- a/tests/ConsumerTest.php +++ b/tests/ConsumerTest.php @@ -63,7 +63,7 @@ public function testEmitsConsumeEvent(): void ->willReturn($envelope); $this->dispatcher->expects($this->at(0))->method('dispatch') - ->with( new PingEvent($queue), 'bernard.ping'); + ->with(new PingEvent($queue), 'bernard.ping'); $this->dispatcher->expects($this->at(1))->method('dispatch') ->with(new EnvelopeEvent($envelope, $queue), 'bernard.invoke'); @@ -250,7 +250,7 @@ public function testWillRejectDispatchOnThrowableError(): void $this->router->route($envelope)->willReturn($receiver); $this->dispatcher->expects(self::at(0))->method('dispatch')->with($this->isInstanceOf(PingEvent::class), 'bernard.ping'); - $this->dispatcher->expects(self::at(1))->method('dispatch')->with($this->isInstanceOf(EnvelopeEvent::class) , 'bernard.invoke'); + $this->dispatcher->expects(self::at(1))->method('dispatch')->with($this->isInstanceOf(EnvelopeEvent::class), 'bernard.invoke'); $this ->dispatcher diff --git a/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php b/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php index a6891762..b124af32 100644 --- a/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php +++ b/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php @@ -1,18 +1,19 @@ pheanstalk = $this->getMockBuilder('Pheanstalk\PheanstalkInterface') - ->setMethods(array( + ->setMethods([ 'putInTube' - )) + ]) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/EnvelopeTest.php b/tests/EnvelopeTest.php index 5fc8d63b..f244aeae 100644 --- a/tests/EnvelopeTest.php +++ b/tests/EnvelopeTest.php @@ -4,9 +4,9 @@ namespace Bernard\Tests; +use Bernard\Envelope; use Bernard\Exception\InvalidOperationException; use Bernard\Message\PlainMessage; -use Bernard\Envelope; final class EnvelopeTest extends \PHPUnit\Framework\TestCase { diff --git a/tests/ProducerTest.php b/tests/ProducerTest.php index 37a87a2b..b57a0ab7 100644 --- a/tests/ProducerTest.php +++ b/tests/ProducerTest.php @@ -56,7 +56,7 @@ public function testItUsesGivenQueueName(): void $this->assertSame($message, $envelope->getMessage()); } - public function testWithDelay() + public function testWithDelay(): void { $message = new PlainMessage('SendNewsletter'); diff --git a/tests/Queue/PersistentQueueTest.php b/tests/Queue/PersistentQueueTest.php index d6ac7f2a..3dfe02bc 100644 --- a/tests/Queue/PersistentQueueTest.php +++ b/tests/Queue/PersistentQueueTest.php @@ -141,7 +141,7 @@ public function testEnqueueDelayed(): void $envelope = new Envelope($this->createMock('Bernard\Message'), 10); $this->serializer->expects($this->once())->method('serialize')->with($this->equalTo($envelope)) - ->will($this->returnValue('serialized message')); + ->willReturn($this->returnValue('serialized message')); $this->driver->expects($this->once())->method('pushMessageWithDelay') ->with($this->equalTo('send-newsletter'), $this->equalTo('serialized message'), $this->equalTo(10)); diff --git a/tests/QueueFactory/PersistentFactoryTest.php b/tests/QueueFactory/PersistentFactoryTest.php index 7f4b8e52..b5fce6ad 100644 --- a/tests/QueueFactory/PersistentFactoryTest.php +++ b/tests/QueueFactory/PersistentFactoryTest.php @@ -11,7 +11,7 @@ class PersistentFactoryTest extends \PHPUnit\Framework\TestCase private $factory; private $connection; - public function setUp(): void + protected function setUp(): void { $this->connection = $this->getMockBuilder('Bernard\Driver') ->disableOriginalConstructor()->getMock(); From b3d61316ca36e96aacadc858dac5a4e695c47f96 Mon Sep 17 00:00:00 2001 From: Eduardo Scarello Date: Thu, 6 Feb 2025 15:35:30 -0300 Subject: [PATCH 105/108] CS fixer --- .github/workflows/php.yml | 35 ------------------- src/DelayableDriver.php | 2 +- .../Delayable/DelayablePheanstalkDriver.php | 2 +- src/Envelope.php | 2 +- src/Producer.php | 2 +- .../DelayablePheanstalkDriverTest.php | 3 +- 6 files changed, 6 insertions(+), 40 deletions(-) delete mode 100644 .github/workflows/php.yml diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml deleted file mode 100644 index d6214483..00000000 --- a/.github/workflows/php.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Tests - -on: - push: - branches: [ master ] - pull_request: - -jobs: - build: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - name: Cache Composer packages - id: composer-cache - uses: actions/cache@v2 - with: - path: vendor - key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} - restore-keys: | - ${{ runner.os }}-php- - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: 7.4 - - - name: Install dependencies - run: | - composer config -g github-oauth.github.com ${{ secrets.GITHUB_TOKEN }} - composer install --prefer-dist --no-progress --ignore-platform-req=php - - - name: Run test suite - run: vendor/bin/phpunit diff --git a/src/DelayableDriver.php b/src/DelayableDriver.php index 529cccb8..d5f6c485 100644 --- a/src/DelayableDriver.php +++ b/src/DelayableDriver.php @@ -13,7 +13,7 @@ interface DelayableDriver extends Driver * * @param string $queueName * @param string $message - * @param int $delay Delay in seconds + * @param int $delay Delay in seconds */ public function pushMessageWithDelay($queueName, $message, $delay): void; } diff --git a/src/Driver/Delayable/DelayablePheanstalkDriver.php b/src/Driver/Delayable/DelayablePheanstalkDriver.php index 01a9b8b5..22105046 100644 --- a/src/Driver/Delayable/DelayablePheanstalkDriver.php +++ b/src/Driver/Delayable/DelayablePheanstalkDriver.php @@ -1,4 +1,5 @@ */ class DelayablePheanstalkDriver extends Pheanstalk\Driver implements DelayableDriver diff --git a/src/Envelope.php b/src/Envelope.php index 21949457..23b023a5 100644 --- a/src/Envelope.php +++ b/src/Envelope.php @@ -25,7 +25,7 @@ public function __construct(Message $message, int $delay = 0) } $this->message = $message; - $this->delay = $delay; + $this->delay = $delay; $this->class = $message::class; $this->timestamp = time(); } diff --git a/src/Producer.php b/src/Producer.php index 05d63bab..003c8f6e 100644 --- a/src/Producer.php +++ b/src/Producer.php @@ -20,7 +20,7 @@ public function __construct(QueueFactory $queues, EventDispatcherInterface $disp /** * @param string|null $queueName - * @param int $delay Delay (in seconds) + * @param int $delay Delay (in seconds) */ public function produce(Message $message, $queueName = null, int $delay = 0): void { diff --git a/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php b/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php index b124af32..07a742dc 100644 --- a/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php +++ b/tests/Driver/Delayable/DelayablePheanstalkDriverTest.php @@ -1,4 +1,5 @@ pheanstalk = $this->getMockBuilder('Pheanstalk\PheanstalkInterface') ->setMethods([ - 'putInTube' + 'putInTube', ]) ->disableOriginalConstructor() ->getMock(); From f24080f9e544c222cc517bf6bc3b97104ab2f9be Mon Sep 17 00:00:00 2001 From: Eduardo Scarello Date: Thu, 6 Feb 2025 15:37:53 -0300 Subject: [PATCH 106/108] CS fixer --- src/DelayableDriver.php | 2 +- src/Producer.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/DelayableDriver.php b/src/DelayableDriver.php index d5f6c485..0bb1b5e5 100644 --- a/src/DelayableDriver.php +++ b/src/DelayableDriver.php @@ -13,7 +13,7 @@ interface DelayableDriver extends Driver * * @param string $queueName * @param string $message - * @param int $delay Delay in seconds + * @param int $delay Delay in seconds */ public function pushMessageWithDelay($queueName, $message, $delay): void; } diff --git a/src/Producer.php b/src/Producer.php index 003c8f6e..8f304522 100644 --- a/src/Producer.php +++ b/src/Producer.php @@ -20,7 +20,7 @@ public function __construct(QueueFactory $queues, EventDispatcherInterface $disp /** * @param string|null $queueName - * @param int $delay Delay (in seconds) + * @param int $delay Delay (in seconds) */ public function produce(Message $message, $queueName = null, int $delay = 0): void { From 05a203abb0ee8c008d6aa8c15a875c90d1df5a84 Mon Sep 17 00:00:00 2001 From: Eduardo Scarello Date: Thu, 6 Feb 2025 15:46:27 -0300 Subject: [PATCH 107/108] CDTM --- src/DelayableDriver.php | 5 +++-- src/Producer.php | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/DelayableDriver.php b/src/DelayableDriver.php index 0bb1b5e5..cd627cd4 100644 --- a/src/DelayableDriver.php +++ b/src/DelayableDriver.php @@ -1,4 +1,5 @@ Date: Thu, 6 Feb 2025 15:54:04 -0300 Subject: [PATCH 108/108] Run php-cs-fixer on this two fucking files --- src/DelayableDriver.php | 2 +- src/Producer.php | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/DelayableDriver.php b/src/DelayableDriver.php index cd627cd4..fb517697 100644 --- a/src/DelayableDriver.php +++ b/src/DelayableDriver.php @@ -14,7 +14,7 @@ interface DelayableDriver extends Driver * * @param string $queueName * @param string $message - * @param int $delay + * @param int $delay */ public function pushMessageWithDelay($queueName, $message, $delay): void; } diff --git a/src/Producer.php b/src/Producer.php index 12ae1fcf..0a8aa012 100644 --- a/src/Producer.php +++ b/src/Producer.php @@ -22,7 +22,6 @@ public function __construct(QueueFactory $queues, EventDispatcherInterface $disp * Produce a message with optional delay in seconds. * * @param string|null $queueName - * @param int $delay */ public function produce(Message $message, $queueName = null, int $delay = 0): void {